Reputation: 128
I am currently trying to compare an array of times with current time and execute certain code.
import os
import datetime as dt
t1 = dt.time(hour=12, minute=45)
t2 = dt.time(hour=12, minute=47)
timetable = [t1, t2]
for i in timetable:
if i[0,1] == dt.datetime.now().hour and i[2,4] == dt.datetime.now().minute:
print("Its working...")
else:
print ("time is now changed")
Currently giving the format like above for specific times.
I tried entering time as string like timetable = ["12:45", "12:50"]
or integer as timetable = [(12),(45),(12),(50)]
but all methods give me different errors.
Upvotes: 0
Views: 122
Reputation: 559
timetable = ["12:45", "12:50"]
for i in timetable:
hour, minute = i.split(':')
if int(hour) == dt.datetime.now().hour and int(minute) == dt.datetime.now().minute:
print("Its working...")
else:
print ("time is now changed")
Upvotes: 1
Reputation: 1247
If you do this:
import datetime as dt
t1 = dt.time(hour=12, minute=45)
t2 = dt.time(hour=12, minute=47)
timetable = [t1, t2]
In your array timetable
, your now have two times.
When you iterate over this array, in your i
you have one time, and then the other. In python, you can actually directly compare times together:
for i in timetable:
# i is a datetime here, you can't access its content with i[0, 1] or anything
# to copare it with the time now, you can do this instead:
if i > dt.datetime.now().time():
# do stuff
Upvotes: 1
Reputation: 86
Change this
if i[0,1] == dt.datetime.now().hour and i[2,4] == dt.datetime.now().minute:
to
if i.hour == dt.datetime.now().hour and i.minute == dt.datetime.now().minute:
timetable contains two datetime objects, not four separate strings of h, m, h, m.
For example, the first i would be datetime(hour=12, minute=45), so extract hour from it with i.hour.
Upvotes: 1