Reputation: 1459
I'm trying to parse a string which has a military time hour value
'10:00:00'
I am able to do this with
>>> datetime.datetime.strptime('10:00:00', '%H:%M:%S').time()
datetime.time(10, 0)
Then I get the current time in a specific time zone:
>>> datetime.datetime.utcnow()+ datetime.timedelta(hours=10)
datetime.datetime(2017, 8, 3, 11, 26, 1, 909000)
What I'm trying to do is compare the time from the string with the current time in utc. But when I compare the values
>>> bne_time_now > tag_time
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't compare datetime.datetime to datetime.time
What I think I need to do is set a default time value when I parse the string but I am not sure how to do this?
Upvotes: 0
Views: 8638
Reputation: 1459
So I managed to get this working:
>>> today = datetime.datetime.utcnow()
>>> today
datetime.datetime(2017, 8, 3, 1, 52, 33, 253000)
>>> datetime.datetime.strptime('10:00:00', '%H:%M:%S').replace(year=today.year, month=today.month, day=today.day)
datetime.datetime(2017, 8, 3, 10, 0)
just posting here in case someone else needs this solution
Upvotes: 0
Reputation: 13
Convert your datetime.datetime
object to a datetime.time
object using the time() method.
>>> (datetime.datetime.utcnow() + datetime.timedelta(hours=10)).time()
datetime.time(11, 33, 51, 523382)
Then you can compare the two time objects.
Upvotes: 1