【发布时间】:2017-12-18 21:32:36
【问题描述】:
我有两个时间戳字符串。我想在几秒钟内找出它们之间的区别。
我试过了:
from time import gmtime, strptime
a = "Mon 11 Dec 2017 13:54:36 -0700"
b = "Mon 11 Dec 2017 13:54:36 -0000"
time1 = strptime(a, "%a %d %b %Y %H:%M:%S %z")
time2 = strptime(b, "%a %d %b %Y %H:%M:%S %z")
time1-time2
出现错误:TypeError: unsupported operand type(s) for -: 'time.struct_time' and 'time.struct_time'
那么,如何使用打包时间计算差异?
我成功使用包 datetime - 在下面的代码中,但我想我读到 datetime 忽略了闰年的秒数,或者类似的东西。因此,我正在尝试使用“时间”:
from datetime import datetime
time1 = datetime.strptime(a, "%a %d %b %Y %H:%M:%S %z")
time2 = datetime.strptime(b, "%a %d %b %Y %H:%M:%S %z")
dif = time1 - time2
print(int(dif.total_seconds()))
非常感谢!
【问题讨论】:
-
"但我想我读到 datetime 忽略了闰年的秒数" 你在哪里读到的?我认为它可能会忽略跳跃 seconds 偶尔添加而没有真正的模式,但 probably 并不重要。
-
对不起,你是对的 - 它忽略了闰秒
-
stackoverflow.com/questions/37928815/… 我想这应该会给你一些见解
-
@user3245256:如果您关心闰秒,
time模块不会做得更好。time和datetime使用相同的底层系统时间信息。 -
另见bugs.python.org/issue23574,为了简单起见,大多数闰秒都被忽略了,特别是因为使用增量来计算未来的时间戳可以保证包含off-by-as-yet-unannounced-leap-seconds不。闰秒仅在 6 个月通知后添加,在处理比这更远的未来建模的日期时间时,您无法以任何有意义的方式考虑它们。