评估时间戳和total_seconds之间的差异 [英] Difference between evaluating timestamp and total_seconds

查看:243
本文介绍了评估时间戳和total_seconds之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在python的datetime中使用两种不同的方法(使用timestamp()或total_seconds())评估两个日期之间的秒数时,得到了不同的结果。为什么是这样?还是我做错了什么?这是我的意思的示例。

When I evaluate the number of seconds between two dates using two different methods (either using timestamp() or total_seconds()) in datetime in python, I get different results. Why is this? Or what am I doing wrong? Here is an example of what I mean.

t1=dt.datetime(1970,6,12,0,0,0)
t2=dt.datetime(1970,1,1,0,0,0)

print(t1.timestamp()-t2.timestamp())
print((t1-t2).total_seconds())

我得到的答案是:
13993200.0
13996800.0

The answers I get are: 13993200.0 13996800.0

推荐答案

差异是由夏令时引起的。如果您的日期之一落在您所在时区的DST范围内,而另一个日期不在DST范围内,那么您的计算将出现一个小时的误差。

The discrepancy is caused by Daylight Savings Time. If one of your dates falls in your timezone's DST range, and the other does not, you end up with an off-by-one hour error in your calculation.

从1966年至1973年,美国夏令时从4月的最后一个星期日开始到十月的最后一个星期日,它解释了 @JoshuaRLi的发现

From 1966 to 1973, DST in the United States ran from the last Sunday in April to the last Sunday in October, which explains @JoshuaRLi's findings.

看起来,当减去两个日期时,它并没有注意DST的差异。 t1-t2 产生 datetime.timedelta(162),相差162天,即使从技术上讲,小时将是162 * 24-1小时(DST跳过的-1占)。 timestamp 正在处理此问题(这两个时间戳都是相对于UTC的,因此DST时间戳正确显示为一个小时,因为产生该时间戳要跳过一个小时)。

It looks like, when subtracting two dates, it's not paying attention to DST discrepancies; t1 - t2 produces datetime.timedelta(162), a difference of 162 days, even though technically, the difference in hours would be 162 * 24 - 1 hours (the - 1 accounting for the DST skip). timestamp is handling this (both timestamps are relative to UTC, so the DST timestamp correctly shows as one hour earlier, because there was an hour skipped to produce it).

这篇关于评估时间戳和total_seconds之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆