Python 3时间:两个时间戳之间的秒数差异

问题描述 投票:-1回答:1

我有两个时间戳字符串。我希望在几秒钟内找到它们之间的差异。

我试过了:

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:不支持的操作数类型 - :'time.struct_time'和'time.struct_time'

那么,如何使用包装时间计算差异?

我成功使用了包日期时间 - 在下面的代码中,但我想我读到日期时间忽略了闰年中的秒数,或者是那种效果。因此,我试图使用'时间':

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()))

非常感谢你!

python time timestamp
1个回答
0
投票

首先,你使用time.strptime,它返回<class 'time.struct_time'>,它不支持substract运算符,一种可能的方法来实现你想要转换为datetime的东西:

from 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,因此您不需要中间转换。

有关datetime支持的操作的更详细说明,请参阅docs supported operations中的here部分。特别是它所说的部分:

如果两者都知道并具有不同的tzinfo属性,则a-b的行为就像a和b首先首先转换为天真的UTC日期时间一样。结果是(a.replace(tzinfo = None) - a.utcoffset()) - (b.replace(tzinfo = None) - b.utcoffset()),但实现永远不会溢出。

在任何情况下,也许你最好的机会是考虑一个替代方法,如在这个answer提出的方法

© www.soinside.com 2019 - 2024. All rights reserved.