Python 检测变量是否为日期时间对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16991948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:09:23  来源:igfitidea点击:

Detect if a variable is a datetime object

pythondatetime

提问by Ryan Saxe

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:

到目前为止,我一直在函数中使用以下 hack 来检测 datetime 对象:

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

除了将对象类型的名称转换为字符串并查看字符串是否包含 hack 之外,还有其他方法可以做到这一点'datetime.datetime'吗?

采纳答案by RichieHindle

You need isinstance(variable, datetime.datetime):

你需要isinstance(variable, datetime.datetime)

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

Update

更新

As noticed by Davos, datetime.datetimeis a subclass of datetime.date, which means that the following would also work:

正如 Davos 所注意到的,datetime.datetime是 的子类datetime.date,这意味着以下内容也适用:

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

熊猫 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:

一个评论提到在 python3.7 中,这个答案中的原始解决方案返回False(它在 python3.4 中工作正常)。在这种情况下,按照达沃斯的评论,您可以执行以下操作:

>>> type(now) is pandas.Timestamp

If you wanted to check whether an item was of type datetime.datetimeOR pandas.Timestamp, just check for both

如果您想检查一个项目是否属于datetime.datetimeOR类型pandas.Timestamp,只需检查两者

>>> (type(now) is datetime.datetime) or (type(now) is pandas.Timestamp)

回答by korylprince

Use isinstance.

使用isinstance.

if isinstance(variable,datetime.datetime):
    print "Yay!"

回答by TehTris

isinstanceis your friend

isinstance是你的朋友

>>> thing = "foo"
>>> isinstance(thing, str)
True

回答by James

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.

虽然使用 isinstance 会做你想做的事,但它不是很“pythonic”,从某种意义上说,请求宽恕比许可更好。

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

回答by Saurav Kumar

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?

我相信以上所有答案仅在日期类型为 datetime.datetime 时才有效。如果日期对象是 datetime.time 或 datetime.date 类型怎么办?

This is how I find a datetime object. It always worked for me. (Python2 & Python3):

这就是我找到日期时间对象的方式。它总是对我有用。(Python2 和 Python3):

import datetime
type(date_obj) in (datetime, datetime.date, datetime.datetime, datetime.time)

Testing in Python2 or Python3 shell:

在 Python2 或 Python3 shell 中测试:

import datetime
d = datetime.datetime.now()  # creating a datetime.datetime object.
date = d.date()  # type(date): datetime.date
time = d.time()  # type(time): datetime.time

type(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

回答by Artur Barseghyan

Note, that datetime.dateobjects aer not considered to be of datetime.datetimetype, while datetime.datetimeobjects are considered to be of datetime.datetype.

请注意,对象通常datetime.date不被视为具有datetime.datetime类型,而datetime.datetime对象则被视为具有datetime.date类型。

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

回答by toast38coza

You can also check using duck typing(as suggested by James).

您还可以使用鸭子类型进行检查(如 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]: