Click here to Skip to main content
15,885,767 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to control devices (module Raspberry Pi) in a certain time period. I make a PHP web to config time value in database mysql. Then I get time from database to compare with time in system (real time clock). If system time is in between time in mysql => led on.
Here is my table(name: time) in mysql:
CSS
start_time                      stop_time
07:00:00 (Type: time)           08:00:00 (Type:time)

And here is my code control device:
Python
import MySQLdb
import RPi.GPIO as GPIO
from datetime import date
import time
db_local = MySQLdb.connect("localhost","root","root","luan_van")
with db_local:
      cur = db_local.cursor(MySQLdb.cursors.DictCursor)
      cur.execute("SELECT * FROM time")
      rows = cur.fetchall()
      start = 0
      stop = 0
      for row in rows:
          start = row['start_time']
          stop = row ['stop_time']
tg = strftime("%H:%M:%S", time.localtime())
if( start < tg < stop):
     GPIO.output(12, True)

It error "can't compare datetime.timedelta to str".
How can I get system time value format "H:M:S"?
Thank for help.
Posted

1 solution

Your problem is not isolating pure time from datetime. Your problem is treating time as string. You cannot compare objects of incompatible types. Comparison time with a string, even it is supposed to represent time, in your opinion, means no more that comparing time with the phrase "I am a little blue balloon in the shy".

You should never try it, even if you can "convert" datetime to string. Correct general approach is calculation of datetime.timedelta for two moments of time. Not only it will give you the check for the identical points in time, but you can also check which moment of time is sooner.

Note that if you want to abstract out the date and compare only the time, you can use datetime.time().

Everything is explained here: https://docs.python.org/2/library/datetime.html[^].

Please try to learn the concepts of typing and basic ideas of programming. Try to work with data, not strings representing data.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900