I have a datetime object in python and I would like create a function to check whether the input is in the morning or afternoon on the day of the datetime (ie, before or aft
Call the datetime.datetime.time() method on the datetime
object and compare it with a datetime.time()
object:
if dt.time() < datetime.time(12):
or just look at the datetime.datetime.hour attribute:
if dt.hour < 12
The latter is simpler, the former gives you more flexibility to compare against times that include a minute component:
if dt.time() < datetime.time(12, 30)
Demo:
>>> import datetime
>>> dt = datetime.datetime.now()
>>> dt
datetime.datetime(2014, 2, 10, 10, 39, 30, 768979)
>>> dt.time() < datetime.time(12)
True
>>> dt.hour < 12
True
>>> dt = dt.replace(hour=20)
>>> dt
datetime.datetime(2014, 2, 10, 20, 39, 30, 768979)
>>> dt.time() < datetime.time(12)
False
>>> dt.hour < datetime.hour
False