Python time differences

后端 未结 4 2091
忘掉有多难
忘掉有多难 2020-12-17 09:07

I have two time objects.

Example

time.struct_time(tm_year=2010, tm_mon=9, tm_mday=24, tm_hour=19, tm_min=13, tm_sec=37, tm_wday=4, tm_yday=267, tm_is         


        
相关标签:
4条回答
  • 2020-12-17 09:49

    There is another way to find the time difference between any two dates (no better than the previous solution, I guess):

     >>> import datetime
     >>> dt1 = datetime.datetime.strptime("10 Oct 10", "%d %b %y")
     >>> dt2 = datetime.datetime.strptime("15 Oct 10", "%d %b %y")
     >>> (dt2 - dt1).days
     5
     >>> (dt2 - dt1).seconds
     0
     >>>
    

    It will give the difference in days or seconds or combination of that. The type for (dt2 - dt1) is datetime.timedelta. Look in the library for further details.

    0 讨论(0)
  • 2020-12-17 09:57

    You can use time.mktime(t) with the struct_time object (passed as "t") to convert it to a "seconds since epoch" floating point value. Then you can subtract those to get difference in seconds, and divide by 60 to get difference in minutes.

    0 讨论(0)
  • 2020-12-17 10:03
    >>> t1 = time.mktime(time.strptime("10 Oct 10", "%d %b %y"))
    >>> t2 = time.mktime(time.strptime("15 Oct 10", "%d %b %y"))
    >>> print(datetime.timedelta(seconds=t2-t1))
    5 days, 0:00:00
    
    0 讨论(0)
  • 2020-12-17 10:04

    Time instances do not support the subtraction operation. Given that one way to solve this would be to convert the time to seconds since epoch and then find the difference, use:

    >>> t1 = time.localtime()
    >>> t1
    time.struct_time(tm_year=2010, tm_mon=10, tm_mday=13, tm_hour=10, tm_min=12, tm_sec=27, tm_wday=2, tm_yday=286, tm_isdst=0)
    >>> t2 = time.gmtime()
    >>> t2
    time.struct_time(tm_year=2010, tm_mon=10, tm_mday=13, tm_hour=4, tm_min=42, tm_sec=37, tm_wday=2, tm_yday=286, tm_isdst=0)
    
    >>> (time.mktime(t1) - time.mktime(t2)) / 60
    329.83333333333331
    
    0 讨论(0)
提交回复
热议问题