gpt4 book ai didi

python - 等格式的时区字段

转载 作者:太空狗 更新时间:2023-10-29 17:03:29 24 4
gpt4 key购买 nike

我有一个应该在 EST 中的时间戳:

2014-10-06T18:06:40-04:56

我理解第一部分:2014-10-06T18:06:40,但不理解 -04:56

-04:56 在这里是什么意思?`

我是这样得到时间戳的:

import datetime
start_time = datetime.datetime(year = 2014,
month = 10,
day = 6,
hour = 18,
tzinfo = pytz.timezone('US/Eastern'))
end_time = start_time + datetime.timedelta(seconds=400)

然后:

end_time.isoformat()

返回:

2014-10-06T18:06:40-04:56

最佳答案

问题是 pytz :

… differs from the documented Python API for tzinfo implementations; if you want to create local wallclock times you need to use the localize() method documented in this document …

再往下,它说:

Unfortunately using the tzinfo argument of the standard datetime constructors "does not work" with pytz for many timezones.

>>> datetime(2002, 10, 27, 12, 0, 0, tzinfo=amsterdam).strftime(fmt)
'2002-10-27 12:00:00 LMT+0020'

因此,您需要按照文档的建议进行操作 — 使用 normalize、构建 UTC 时间并使用 astimezone 等。您想要哪一个取决于您的具体内容正在尝试做。例如:

>>> from datetime import datetime
>>> from pytz import timezone
>>> utc = timezone('UTC')
>>> eastern = timezone('US/Eastern')
>>> datetime(2014, 10, 6, 18, tzinfo=eastern).isoformat()
'2014-10-06T18:00:00-04:56'
>>> eastern.normalize(datetime(2014, 10, 6, 18, tzinfo=eastern)).isoformat()
'2014-10-06T18:56:00-04:00'
>>> datetime(2014, 10, 6, 18, tzinfo=utc).astimezone(eastern).isoformat()
'2014-10-06T14:00:00-04:00'
>>> eastern.localize(datetime(2014, 10, 6, 18)).isoformat()
'2014-10-06T18:00:00-04:00'

我想这是你想要的最后一个。正如 localize 的文档所说:

Convert naive time to local time.

This method should be used to construct localtimes, rather than passing a tzinfo argument to a datetime constructor.

而且我认为构造本地时间正是您在这里想要的。


如果您想知道为什么……好吧,如果您查看 Olson 数据库中的数据,或者只是打印出 eastern._utcoffset,您会看到-1 天,+68640 分钟。那是 19.0166+ 小时,而不是 19。为什么?因为每个时区都是用它的起始偏移量定义的,并从那里进行调整。东部基于 1883 年 11 月 18 日 12:03:58 的纽约时区,此时距格林威治标准时间为 -04:56:02。对从 1920 年开始的日期进行了调整,减去了额外的 00:03:58。当然,DST 每年来回调整一小时。所以,截至目前,东部时间是 -04:00,但不知道它应该代表什么日期,它是 -04:56。而且,因为 datetime 只是询问时区的偏移量,而不是它在特定时间的偏移量,所以它就是这样。


最后一件事:EST 是东部标准时间,即 -05:00。这不是 2014 年 10 月 6 日美国任何地点的时区,因为在 2014 年,美国的夏令时为 11 月 2 日。 (印第安纳州曾经有一些县在夏季使用 EST,但现在不再有。)您正在寻找的是 EDT,东部夏令时,即 -04:00。或者,当然,ET,这是夏季的 EDT 和冬季的 EST,这是您通过查找 'US/Eastern''America/New_York' .

关于python - 等格式的时区字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26264897/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com