Reputation: 1935
I'm trying to figure out if a unix timestamp is after 21:00. However, I'm having type errors.
This is my code:
from datetime import datetime, time
theTime=1497204737
the_date = (
datetime.fromtimestamp(
int(theTime)
).strftime('%H:%M:%S')
)
if the_date >= time(21,00):
print("we did it!")
I keep getting this error:
TypeError: '<=' not supported between instances of 'str' and 'datetime.time'
How can I fix this issue?
Upvotes: 1
Views: 2742
Reputation: 152647
The problem is that you convert the timestamp to a datetime
but then you convert it to a string again:
>>> the_date = datetime.fromtimestamp(int(theTime)).strftime('%H:%M:%S')
>>> type(the_date)
str
There are several ways to make it work:
For example you could simply keep the timestamp as datetime
and compare the hours
:
from datetime import datetime, time
theTime=1497204737
the_date = datetime.fromtimestamp(int(theTime))
if the_date.hour >= 21:
print("we did it!")
or convert the datetime
to a time
and compare the time
s:
if time(the_date.hour, the_date.minute) >= time(21, 0):
print("we did it!")
Upvotes: 1