将山区标准时间转换为东部标准时间在Python中的实现

5
我有一个时间日期对象,包含日期和时间。
例如:
    d = (2011,11,1,8,11,22)  (24 hour time time format)

但是这个时间戳是在山区标准时间(亚利桑那州菲尼克斯)。现在我想把这个时间转换成东部标准时间... 现在这只是时间差调整... 但是还有夏令时问题。我想知道是否有内置方法来处理夏令时以调整时区。
3个回答

5

使用pytz进行时区转换。 pytz会考虑夏令时,请参阅此链接。您需要一个辅助函数,例如:

def convert(dte, fromZone, toZone):
    fromZone, toZone = pytz.timezone(fromZone), pytz.timezone(toZone)
    return fromZone.localize(dte, is_dst=True).astimezone(toZone)

可能缺少 toZone.normalize() 调用。在 DST 转换期间,is_dst=True 一半的时间是错误的。 - jfs

4
你要找的库是pytz,具体使用方法是使用localize()方法。
Pytz不在标准库中,但可以通过pip或easy_install获取。

tz.localize() 将一个 naive datetime 对象转换为 tz 时区的 aware datetime 对象。它不会将一个时区转换为另一个时区。 - jfs

1

基于pytz文档中的示例,将一个无时区信息的日期时间对象转换为另一个时区:

from datetime import datetime
import pytz

def convert(naive_dt, from_tz, to_tz, is_dst=None):
    """Convert naive_dt from from_tz timezone to to_tz timezone.

    if is_dst is None then it raises an exception for ambiguous times
    e.g., 2002-10-27 01:30:00 in US/Eastern
    """
    from_dt = from_tz.localize(naive_dt, is_dst=is_dst)
    return to_tz.normalize(from_dt.astimezone(to_tz))

ph_tz = pytz.timezone('America/Phoenix')
east_tz = pytz.timezone('US/Eastern')
from_naive_dt = datetime(2011, 11, 1, 8, 11, 22)
east_dt = convert(from_naive_dt, ph_tz, east_tz)

def p(dt):
    print(dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'))

p(east_dt)  # -> 2011-11-01 11:11:22 EDT-0400

这是来自pytz文档的一个模糊时间示例:
ambiguous_dt = datetime(2002, 10, 27, 1, 30)
p(convert(ambiguous_dt, east_tz, pytz.utc, is_dst=True))
p(convert(ambiguous_dt, east_tz, pytz.utc, is_dst=False))
p(convert(ambiguous_dt, east_tz, pytz.utc, is_dst=None)) # raise exception
assert 0 # unreachable

输出:

2002-10-27 05:30:00 UTC+0000 # ambiguous_dt is interpreted as EDT-0400
2002-10-27 06:30:00 UTC+0000 # ambiguous_dt is interpreted as EST-0500
pytz.exceptions.AmbiguousTimeError: 2002-10-27 01:30:00

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接