检测变量是否为日期时间对象 [英] 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'
除了将对象类型的名称转换为字符串并查看字符串是否包含'datetime.datetime'
?
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(变量,datetime.datetime)
:
>>> import datetime
>>> now = datetime.datetime.now()
>>> isinstance(now, datetime.datetime)
True
更新
达沃斯注意到, datetime.datetime
是 datetime.date
,这意味着以下内容也可以使用:
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
熊猫 Timestamp
Pandas Timestamp
有一条评论提到在python3.7中,此答案中的原始解决方案返回 False
(在python3.4中工作正常)。在这种情况下,按照达沃斯的评论,您可以执行以下操作:
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
如果要检查某项是否为 datetime.datetime
或 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)
这篇关于检测变量是否为日期时间对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!