単純な日時オブジェクトをあるタイムゾーンから別のタイムゾーンに変換する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 docs のあいまいな時間の例を次に示します。
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