I have a variable and I need to know if it is a datetime object.
So far I have been using the following hack in the function to detect datetime object:
i
You can also check using duck typing (as suggested by James).
Here is an example:
from datetime import date, datetime
def is_datetime(dt):
"""
Returns True if is datetime
Returns False if is date
Returns None if it is neither of these things
"""
try:
dt.date()
return True
except:
if isinstance(dt, date):
return False
return None
Results:
In [8]: dt = date.today()
In [9]: tm = datetime.now()
In [10]: is_datetime(dt)
Out[11]: False
In [12]: is_datetime(tm)
Out[13]: True
In [14]: is_datetime("sdf")
In [15]: