我有两个时间戳字符串。 我想在几秒钟内找到它们之间的区别。
我试过了:
1
2
3
4
5
6
7
8from 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:-:" time.struct_time"和" time.struct_time"的不受支持的操作数类型
那么,如何使用打包时间计算差异?
我成功使用了包datetime-在下面的代码中,但是我想我读到datetime忽略了leap年中的秒数或类似的结果。 因此,我正在尝试使用"时间":
1
2
3
4
5from 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()))
非常感谢你!
"但是我想我读到日期时间忽略了leap年的秒数",您在哪里读到的?我认为它可能会忽略偶尔添加的leap秒,而没有真正的模式,但这可能无关紧要。
抱歉,您是对的-它忽略了leap秒
stackoverflow.com/questions/37928815/我认为这应该给您一些见识
@ user3245256:如果您关心leap秒,则time模块不会做得更好。 time和datetime使用相同的基础系统时间信息。
另请参见bugs.python.org/issue23574,为简单起见,大多数leap秒都被忽略了,特别是因为使用delta来计算未来的时间戳可以确保包含不存在的尚未宣布的le秒。 6秒仅需6个月的通知,因此在处理远期建模的日期时间时,您无法以任何有意义的方式解释它们。
非常感谢你。是的,这很有道理。在这种情况下,这并不重要,我的问题不是超级有用。我的日期时间解决方案有效,所以谢谢!
首先,您正在使用time.strptime,它返回,并且它不支持减法运算符,一种实现所需的方法是将其转换为datetime:
1
2
3
4
5
6
7
8
9
10
11from datetime import datetime
from time import mktime
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")
print(datetime.fromtimestamp(mktime(time1))-datetime.fromtimestamp(mktime(time2)))
甚至更好,请使用datetime.datetime.strptime,这样就不需要中间转换。
有关日期时间支持的操作的详细说明,请参阅此处文档中的supported operations部分。 特别是其中说:
If both are aware and have different tzinfo attributes, a-b acts as if
a and b were first converted to naive UTC datetimes first. The result
is (a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
- b.utcoffset()) except that the implementation never overflows.
无论如何,也许您最好的机会是考虑使用另一种方法,例如本答案中提出的方法
我尝试了上面的代码。 打印:0:00:00
@ user3245256是的,上面的代码向您展示了如何使用日期时间的-运算符,因为您会看到它会忽略字符串a和b的最后一部分。 尝试将b更改为b ="Mon 11 Dec 2017 13:54:31 -0000"之类的内容,以便观察差异。
抱歉,我不确定我是否理解。 我的b是它的意思。 结果应该相差7小时,以秒为单位。
编辑了我的答案