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

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

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

17条回答
  •  粉色の甜心
    2020-11-22 11:57

    Based on @Attaque great answer, I propose a shorter simplified version of the datetime difference calculator:

    seconds_mapping = {
        'y': 31536000,
        'm': 2628002.88, # this is approximate, 365 / 12; use with caution
        'w': 604800,
        'd': 86400,
        'h': 3600,
        'min': 60,
        's': 1,
        'mil': 0.001,
    }
    
    def get_duration(d1, d2, interval, with_reminder=False):
        if with_reminder:
            return divmod((d2 - d1).total_seconds(), seconds_mapping[interval])
        else:
            return (d2 - d1).total_seconds() / seconds_mapping[interval]
    

    I've changed it to avoid declaring repetetive functions, removed the pretty print default interval and added support for milliseconds, weeks and ISO months (bare in mind months are just approximate, based on assumption that each month is equal to 365/12).

    Which produces:

    d1 = datetime(2011, 3, 1, 1, 1, 1, 1000)
    d2 = datetime(2011, 4, 1, 1, 1, 1, 2500)
    
    print(get_duration(d1, d2, 'y', True))      # => (0.0, 2678400.0015)
    print(get_duration(d1, d2, 'm', True))      # => (1.0, 50397.12149999989)
    print(get_duration(d1, d2, 'w', True))      # => (4.0, 259200.00149999978)
    print(get_duration(d1, d2, 'd', True))      # => (31.0, 0.0014999997802078724)
    print(get_duration(d1, d2, 'h', True))      # => (744.0, 0.0014999997802078724)
    print(get_duration(d1, d2, 'min', True))    # => (44640.0, 0.0014999997802078724)
    print(get_duration(d1, d2, 's', True))      # => (2678400.0, 0.0014999997802078724)
    print(get_duration(d1, d2, 'mil', True))    # => (2678400001.0, 0.0004999997244524721)
    
    print(get_duration(d1, d2, 'y', False))     # => 0.08493150689687975
    print(get_duration(d1, d2, 'm', False))     # => 1.019176965856293
    print(get_duration(d1, d2, 'w', False))     # => 4.428571431051587
    print(get_duration(d1, d2, 'd', False))     # => 31.00000001736111
    print(get_duration(d1, d2, 'h', False))     # => 744.0000004166666
    print(get_duration(d1, d2, 'min', False))   # => 44640.000024999994
    print(get_duration(d1, d2, 's', False))     # => 2678400.0015
    print(get_duration(d1, d2, 'mil', False))   # => 2678400001.4999995
    

提交回复
热议问题