简体   繁体   English

datetime模块如何知道本地时区?

[英]How is the datetime module aware of the local time zone?

The following code shows the difference between my local time (US central time) and UTC for every day over one year: 以下代码显示一年中每天的本地时间(美国中部时间)与UTC之间的时差:

import datetime
startTs = 1293808443
intvl = 24 * 3600
for day in range(365):
    ts = startTs + day * intvl
    localTs = datetime.datetime.fromtimestamp(ts)
    utcTs = datetime.datetime.utcfromtimestamp(ts)
    print("%s\t%s" % (utcTs.strftime("%Y-%m-%d %H:%M:%S"), (utcTs - localTs)))

The result: 结果:

2010-12-31 15:14:03 6:00:00
2011-01-01 15:14:03 6:00:00
...
2011-03-11 15:14:03 6:00:00
2011-03-12 15:14:03 6:00:00
2011-03-13 15:14:03 5:00:00
2011-03-14 15:14:03 5:00:00
...
2011-11-04 15:14:03 5:00:00
2011-11-05 15:14:03 5:00:00
2011-11-06 15:14:03 6:00:00
2011-11-07 15:14:03 6:00:00
...
2011-12-29 15:14:03 6:00:00
2011-12-30 15:14:03 6:00:00

Without my specifying any time zone info, the datetime module seems to be aware not only of the time difference between my local time zone and UTC, but also of when daylight saving time starts and ends. 在没有指定任何时区信息的情况下,datetime模块似乎不仅知道我的本地时区与UTC之间的时差,而且还知道夏令时的开始和结束时间。 This seems to contradict this answer to a similar question. 这似乎与类似问题的答案相矛盾。 Am I mistaken in my conclusion? 我的结论有误吗? If not, how do I get this time zone info from the OS/datetime module? 如果没有,如何从OS / datetime模块获取该时区信息?

Check out datetime docs . 查看datetime文档

In short, datetime and time objects have an optional timezone attribute, tzinfo that can be set to an instance of a subclass of the abstract tzinfo class. 简而言之,datetime和time对象具有可选的时区属性tzinfo,可以将其设置为抽象tzinfo类的子类的实例。

These tzinfo objects capture information about the offset from UTC time, the time zone name, and whether Daylight Saving Time is in effect, only one concrete tzinfo class, the timezone class, is supplied by the datetime module. 这些tzinfo对象捕获有关UTC时间的偏移量,时区名称以及夏时制是否有效的信息,datetime模块仅提供一个具体的tzinfo类(时区类)。

The timezone class can represent simple timezones with fixed offset from UTC, such as UTC itself or North American EST and EDT timezones. 时区类可以表示与UTC具有固定偏移量的简单时区,例如UTC本身或北美EST和EDT时区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM