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:
if 'datetime.datetime' in str(type(variable)):
print('yes')
But there really should be a way to detect what type of object something is. Just like I can do:
if type(variable) is str: print 'yes'
Is there a way to do this other than the hack of turning the name of the object type into a string and seeing if the string contains 'datetime.datetime'
?
isinstance
is your friendYou can also check using duck typing (as suggested by James).
Here is an example:
Results:
While using isinstance will do what you want, it is not very 'pythonic', in the sense that it is better to ask forgiveness than permission.
You need
isinstance(variable, datetime.datetime)
:Update
As noticed by Davos,
datetime.datetime
is a subclass ofdatetime.date
, which means that the following would also work:Perhaps the best approach would be just testing the type (as suggested by Davos):
Pandas
Timestamp
One comment mentioned that in python3.7, that the original solution in this answer returns
False
(it works fine in python3.4). In that case, following Davos's comments, you could do following:If you wanted to check whether an item was of type
datetime.datetime
ORpandas.Timestamp
, just check for bothUse
isinstance
.Note, that
datetime.date
objects aer not considered to be ofdatetime.datetime
type, whiledatetime.datetime
objects are considered to be ofdatetime.date
type.