Detect if a variable is a datetime object

2020-05-24 19:51发布

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

7条回答
Juvenile、少年°
2楼-- · 2020-05-24 20:12

isinstance is your friend

>>> thing = "foo"
>>> isinstance(thing, str)
True
查看更多
萌系小妹纸
3楼-- · 2020-05-24 20:23

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]:
查看更多
够拽才男人
4楼-- · 2020-05-24 20:24

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.

try:
    do_something_small_with_object() #Part of the code that may raise an 
                                     #exception if its the wrong object
except StandardError:
    handle_case()

else:
    do_everything_else()
查看更多
做个烂人
5楼-- · 2020-05-24 20:25

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)
查看更多
▲ chillily
6楼-- · 2020-05-24 20:28

Use isinstance.

if isinstance(variable,datetime.datetime):
    print "Yay!"
查看更多
对你真心纯属浪费
7楼-- · 2020-05-24 20:28

Note, that datetime.date objects aer 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)                                                                                                
>>> False

isinstance(now, datetime.datetime)                                                                                                  
>>> True

isinstance(now, datetime.date)                                                                                                      
>>> True

isinstance(now, datetime.datetime)                                                                                                  
>>> True
查看更多
登录 后发表回答