Python: how can I check whether an object is of type datetime.date?

后端 未结 7 1224
既然无缘
既然无缘 2020-12-24 10:16

I have tried a few obvious options but none of them works:

In [150]: x
Out[150]: datetime.date(2012, 9, 1)

In [151]: type(x)
Out[151]: datetime.date

In [15         


        
7条回答
  •  余生分开走
    2020-12-24 10:51

    According to documentation class date is a parent for class datetime. And isinstance() method will give you True in all cases. If you need to distinguish datetime from date you should check name of the class

    import datetime
    
    datetime.datetime.now().__class__.__name__ == 'date' #False
    datetime.datetime.now().__class__.__name__ == 'datetime' #True
    datetime.date.today().__class__.__name__ == 'date' #True
    datetime.date.today().__class__.__name__ == 'datetime' #False
    

    I've faced with this problem when i have different formatting rules for dates and dates with time

提交回复
热议问题