Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I sort out an object is datetime or date in python?

I am trying to develop a logic that depends on the type of the input being date or datetime. To achieve this goal, I used isinstance with datetime.date and datetime.datetime. Unfortunately, it seems like that a datetime.datetime object is considered an instance of datetime.date.

import datetime

date_obj = datetime.date.today()
datetime_obj = datetime.datetime.now()


type(date_obj)
# <class 'datetime.date'>

type(datetime_obj)
# <class 'datetime.datetime'>


isinstance(date_obj, datetime.date)
# True
isinstance(datetime_obj, datetime.date)
# True


isinstance(date_obj, datetime.datetime)
# False
isinstance(datetime_obj, datetime.date)
# True

I suspected that datetime.date might be considered a subclass of datetime.datetime but that’s not the case:

issubclass(datetime.date, datetime.datetime)
# False
issubclass(datetime.datetime, datetime.date)
# True

What’s the pythonic way of figureing out whether an object is a date or a datetime?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

P.S. I checked this related question, but that doesn’t resolve my issue.

>Solution :

You can retrieve the exact type of the objects with type, and check whether it’s date or datetime using is:

>>> type(date_obj) is datetime.date
True
>>> type(date_obj) is datetime.datetime
False

>>> type(datetime_obj) is datetime.date
False
>>> type(datetime_obj) is datetime.datetime
True

Note that type objects are unique, so comparing them using is is well defined.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading