How can I compare a date and a datetime in Python?

后端 未结 5 1299
野趣味
野趣味 2020-12-01 03:12

Here\'s a little snippet that I\'m trying execute:

>>> from datetime import *
>>> item_date = datetime.strptime(\'7/16/10\', \"%m/%d/%y\")
         


        
5条回答
  •  感动是毒
    2020-12-01 03:51

    In my case, I get two objects in and I don't know if it's date or timedate objects. Converting to date won't be good as I'd be dropping information - two timedate objects with the same date should be sorted correctly. I'm OK with the dates being sorted before the datetime with same date.

    I think I will use strftime before comparing:

    >>> foo=datetime.date(2015,1,10)
    >>> bar=datetime.datetime(2015,2,11,15,00)
    >>> foo.strftime('%F%H%M%S') > bar.strftime('%F%H%M%S')
    False
    >>> foo.strftime('%F%H%M%S') < bar.strftime('%F%H%M%S')
    True
    

    Not elegant, but should work out. I think it would be better if Python wouldn't raise the error, I see no reasons why a datetime shouldn't be comparable with a date. This behaviour is consistent in python2 and python3.

提交回复
热议问题