Detect if a variable is a datetime object

后端 未结 7 1346
情深已故
情深已故 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:08

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

提交回复
热议问题