Detect if a variable is a datetime object

后端 未结 7 1349
情深已故
情深已故 2021-02-02 05:31

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:

i         


        
7条回答
  •  猫巷女王i
    2021-02-02 06:24

    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)
    

提交回复
热议问题