Python的夏令时 [英] Daylight savings time in Python

查看:190
本文介绍了Python的夏令时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个处理很多时区并跨越时区的程序。我最常处理的两件事是从现在创建一个日期时间对象,然后本地化一个简单的日期时间对象。

I am writing a program which deals a lot with timezones and crossing them. The two things I deal with most are creating a datetime object from "now" and then localizing a naive datetime object.

要从现在开始在太平洋时区中创建日期时间对象,我目前正在执行此操作(python 2.7.2 +)

To create a datetime object from now in the pacific timezone, I am currently doing this (python 2.7.2+)

from datetime import datetime
import pytz
la = pytz.timezone("America/Los_Angeles")
now = datetime.now(la)

关于DST,这是否正确?如果没有,我想应该这样做:

Is this correct with regards to DST? If not, I suppose I should be doing:

now2 = la.localize(datetime.now())

我的问题是为什么?有人可以告诉我第一个错误而第二个秒是正确的情况吗?

My question is why? Can anyone show me a case where the first is wrong and the seconds is right?

关于我的秒数问题,假设我从某些用户输入中得到了一个简单的日期和时间在2012年9月1日上午8:00(加利福尼亚州洛杉矶)。是使日期时间像这样的正确方法:

As for my seconds question, suppose I had a naive date and time from some user input for 9/1/2012 at 8:00am in Los Angeles, CA. Is the right way to make the datetime like this:

la.localize(datetime(2012, 9, 1, 8, 0))

如果没有,我应该如何构建这些日期时间?

If not, how should I be building these datetimes?

推荐答案

来自 pytz文档


处理时间的首选方法是始终在UTC中工作,仅在生成人类可读的输出时才转换为本地时间。

The preferred way of dealing with times is to always work in UTC, converting to localtime only when generating output to be read by humans.

因此,理想情况下,您应该使用 utcnow 而不是 now

So ideally you should be using utcnow instead of now.

由于某种原因,您的双手被绑住了,并且需要与当地时间打交道,尝试这样做仍然会遇到问题如果您在夏令时过渡窗口中进行操作,请对当前时间进行本地化。相同的 datetime 可能会出现两次,一次是在白天,另一次是在标准时间,而 localize 方法不会知道如何解决冲突,除非您使用 is_dst 参数明确指出。

Assuming for some reason that your hands are tied and you need to work with local times, you can still run into a problem with trying to localize the current time if you're doing it during the daylight saving transition window. The same datetime might occur twice, once during daylight time and again during standard time, and the localize method doesn't know how to settle the conflict unless you tell it explicitly with the is_dst parameter.

因此,获取当前的UTC时间:

So to get the current UTC time:

utc = pytz.timezone('UTC')
now = utc.localize(datetime.datetime.utcnow())

并将其转换为本地时间(但仅在必须时):

And to convert it to your local time (but only when you must):

la = pytz.timezone('America/Los_Angeles')
local_time = now.astimezone(la)

编辑:如 @ JF塞巴斯蒂安(Sebastian),使用 datetime.now(tz)的第一个示例在所有情况下均适用。如上文所述,您的第二个示例在秋天过渡期间失败了。我仍然提倡使用UTC代替本地时间来显示所有内容。

as pointed out in the comments by @J.F. Sebastian, your first example using datetime.now(tz) will work in all cases. Your second example fails during the fall transition as I outlined above. I still advocate using UTC instead of local time for everything except display.

这篇关于Python的夏令时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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