Detect If A Variable Is A Datetime Object
Solution 1:
You need isinstance(variable, datetime.datetime):
>>>import datetime>>>now = datetime.datetime.now()>>>isinstance(now, datetime.datetime)
True
Update
As noticed by Davos, datetime.datetime is a subclass of datetime.date, which means that the following would also work:
>>> isinstance(now, datetime.date)
TruePerhaps the best approach would be just testing the type (as suggested by Davos):
>>> type(now) is datetime.date
False>>> type(now) is datetime.datetime
TruePandas 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:
>>>type(now) is pandas.TimestampIf you wanted to check whether an item was of type datetime.datetime OR pandas.Timestamp, just check for both
>>>(type(now) is datetime.datetime) or (type(now) is pandas.Timestamp)Solution 2:
Use isinstance.
ifisinstance(variable,datetime.datetime):
print"Yay!"Solution 3:
Note, that datetime.date objects are not considered to be of datetime.datetime type, while datetime.datetime objects are considered to be of datetime.date type.
import datetime
today = datetime.date.today()
now = datetime.datetime.now()
isinstance(today, datetime.datetime)
>>> Falseisinstance(now, datetime.datetime)
>>> Trueisinstance(now, datetime.date)
>>> Trueisinstance(now, datetime.datetime)
>>> TrueSolution 4:
I believe all the above answer will work only if date is of type datetime.datetime. What if the date object is of type datetime.time or datetime.date?
This is how I find a datetime object. It always worked for me. (Python2 & Python3):
import datetime
type(date_obj) in (datetime, datetime.date, datetime.datetime, datetime.time)
Testing in Python2 or Python3 shell:
import datetime
d = datetime.datetime.now() # creating a datetime.datetime object.
date = d.date() # type(date): datetime.datetime = d.time() # type(time): datetime.timetype(d) in (datetime, datetime.date, datetime.datetime, datetime.time)
True
type(date) in (datetime, datetime.date, datetime.datetime, datetime.time)
True
type(time) in (datetime, datetime.date, datetime.datetime, datetime.time)
True
Solution 5:
isinstance is your friend
>>>thing = "foo">>>isinstance(thing, str)
True
Post a Comment for "Detect If A Variable Is A Datetime Object"