Detect if a variable is a datetime object

后端 未结 7 1336
情深已故
情深已故 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条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-02 06:23

    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?

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

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

    Testing in Python2 or 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
    

提交回复
热议问题