How to check if a date time is before midday

后端 未结 1 1133
礼貌的吻别
礼貌的吻别 2021-01-18 09:30

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

相关标签:
1条回答
  • 2021-01-18 09:49

    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
    
    0 讨论(0)
提交回复
热议问题