pytz:为什么这些不同的方法给出不同的 UTC 偏移量?
使用 pytz 在特定时区创建 datetime
对象时,根据我使用的是 datetime.datetime()
还是 datetime.datetime,我会得到不同的 UTC 偏移量。现在()。
now()
似乎给出了正确的时区 UTC 偏移量,datetime()
给出了我无法识别的偏移量。
为什么它们不同? datetime()
分配的偏移量有什么意义?
这是我的代码:
import datetime
import pytz
la_paz = pytz.timezone('America/La_Paz')
a = datetime.datetime.now(la_paz)
print a, a.utcoffset()
# 2011-03-22 05:30:13-04:00 -1 day, 20:00:00
# -4 hours is the correct UTC offset for La Paz
b = datetime.datetime(2011, 03, 22, 5, 30, tzinfo=la_paz)
print b, b.utcoffset()
# 2011-03-22 05:30:00-04:33 -1 day, 19:27:00
# What is the significance of -4:33?
When creating a datetime
object in a specific time zone using pytz I get a different UTC offset depending on whether I use datetime.datetime()
or datetime.datetime.now()
.
now()
seems to give the correct UTC offset for the time zone, datetime()
gives an offset that I don't recognise.
Why are they different? What is the significance of the offset that datetime()
assigns?
Here's my code:
import datetime
import pytz
la_paz = pytz.timezone('America/La_Paz')
a = datetime.datetime.now(la_paz)
print a, a.utcoffset()
# 2011-03-22 05:30:13-04:00 -1 day, 20:00:00
# -4 hours is the correct UTC offset for La Paz
b = datetime.datetime(2011, 03, 22, 5, 30, tzinfo=la_paz)
print b, b.utcoffset()
# 2011-03-22 05:30:00-04:33 -1 day, 19:27:00
# What is the significance of -4:33?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
似乎
datetime()
默认情况下将使用该地区第一个记录的时区,并且在许多情况下(例如在拉巴斯),这是旧的并且不再有效。相反,必须先创建日期时间,然后进行本地化,如下所示:
now()
似乎会自动进行本地化。It seems that
datetime()
will use the first recorded timezone for the region by default, and in many cases (like in La Paz) this is old and no longer valid.The datetime must instead be created naive and then localised like so:
now()
appears to do the localization automatically.来自 pytz 文档:
此库仅支持两种方式建立本地化时间。第一种是使用 pytz 库提供的 localize() 方法。这用于本地化原始日期时间(没有时区信息的日期时间):
构建本地化时间的第二种方法是使用标准 astimezone() 方法转换现有的本地化时间:
或者换句话说:
pytz 不支持
From the pytz documentation:
This library only supports two ways of building a localized time. The first is to use the localize() method provided by the pytz library. This is used to localize a naive datetime (datetime with no timezone information):
The second way of building a localized time is by converting an existing localized time using the standard astimezone() method:
Or put another way:
Is not supported by pytz