Python时差
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3920820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python time differences
提问by user469652
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_isdst=-1)
time.struct_time(tm_year=2010, tm_mon=9, tm_mday=25, tm_hour=13, tm_min=7, tm_sec=25, tm_wday=5, tm_yday=268, tm_isdst=-1)
I want to have the difference of those two. How could I do that? I need minutes and seconds only, as well as the duration of those two.
我想有这两者的区别。我怎么能那样做?我只需要分钟和秒,以及这两者的持续时间。
采纳答案by Manoj Govindan
Timeinstances 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:
Time实例不支持减法运算。鉴于解决此问题的一种方法是将时间转换为自纪元以来的秒数,然后找到差异,请使用:
>>> 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
回答by DerfK
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.
您可以使用time.mktime(t)struct_time 对象(作为“t”传递)将其转换为“自纪元以来的秒数”浮点值。然后你可以减去这些以获得以秒为单位的差异,然后除以 60 以获得以分钟为单位的差异。
回答by jweyrich
>>> 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
回答by Somum
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 libraryfor further details.
它将以天数或秒数或两者的组合给出差异。(dt2 - dt1) 的类型是 datetime.timedelta。在图书馆中查看更多详细信息。

