Lucky Lucky - 1 month ago 6
Python Question

Python how to save datetime.strptime in datetime.time format

So I was trying to make a simple code using datetime and came across an error.

import time
from datetime import datetime
x = True
b = datetime.strptime("06:10", "%H:%M")
while x == True:
a = datetime.now().time()
print(a)
if a > b:
x = False
time.sleep(0.945)


As a result I get

TypeError: unorderable types: datetime.time() > datetime.datetime()


So I was wondering if it's possible to save a datetime.strptime in the datetime.time() format.

Thanks in advance

Answer

When you call datetime.now() you get actually a datetime.datetime object. So you could already compare both values if you remote .time(). An alternative would be (if you don't care about the date) that you actually get only the time of b by doing b = b.time().

Comments