Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if a variable is a datetime object

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'?

like image 996
Ryan Saxe Avatar asked Jun 07 '13 19:06

Ryan Saxe


People also ask

What type is datetime Python?

In Python, date and time are not a data type of their own, but a module named datetime can be imported to work with the date as well as time. Python Datetime module comes built into Python, so there is no need to install it externally. Python Datetime module supplies classes to work with date and time.

Is date an object in Python?

A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.

How do you check the type of a variable in Python?

Use the type() Function to Check Variable Type in Python To check the type of a variable, you can use the type() function, which takes the variable as an input. Inside this function, you have to pass either the variable name or the value itself. And it will return the variable data type.


1 Answers

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) True 

Perhaps the best approach would be just testing the type (as suggested by Davos):

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

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:

>>> type(now) is pandas.Timestamp 

If 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) 
like image 196
RichieHindle Avatar answered Sep 23 '22 23:09

RichieHindle