How do I find the time difference between two datetime objects in python?

前端 未结 17 998
無奈伤痛
無奈伤痛 2020-11-22 11:06

How do I tell the time difference in minutes between two datetime objects?

17条回答
  •  不思量自难忘°
    2020-11-22 11:41

    If a, b are datetime objects then to find the time difference between them in Python 3:

    from datetime import timedelta
    
    time_difference = a - b
    time_difference_in_minutes = time_difference / timedelta(minutes=1)
    

    On earlier Python versions:

    time_difference_in_minutes = time_difference.total_seconds() / 60
    

    If a, b are naive datetime objects such as returned by datetime.now() then the result may be wrong if the objects represent local time with different UTC offsets e.g., around DST transitions or for past/future dates. More details: Find if 24 hrs have passed between datetimes - Python.

    To get reliable results, use UTC time or timezone-aware datetime objects.

提交回复
热议问题