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



我有两个时间戳字符串。我想在几秒钟内找到它们之间的区别。

我尝试过:

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'

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

我成功地使用了Package DateTime-在下面的代码中,但是我想我读到DateTime忽略了LEAP年份的秒数,或者忽略了这种效果。因此,我试图使用"时间":

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

非常感谢!

首先,您使用的是time.strptime,它返回 <class 'time.struct_time'>,并且不支持cistract运算符,这是实现您想要的东西的一种可能方法:

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支持操作的更详细说明,请参阅此处的文档中的supported operations节。特别是所说的部分:

如果两者都知道并且具有不同的tzinfo属性,则a-b的作用 首先将A和B首先转换为NAIVE UTC数据。结果 is(a.replace(tzinfo = none) - a.utcoffset()) - (b.replace(tzinfo = none) -b。utcoffset())除了实现永远不会溢出。

无论如何,也许您最好的机会是考虑一种替代方法,例如此答案中提出的方法

最新更新