use*_*424 2 python timezone pytz
我在python中编写了以下脚本,将datetime从任何给定的时区转换为EST.
from datetime import datetime, timedelta
from pytz import timezone
import pytz
utc = pytz.utc
# Converts char representation of int to numeric representation '121'->121, '-1729'->-1729
def toInt(ch):
ret = 0
minus = False
if ch[0] == '-':
ch = ch[1:]
minus = True
for c in ch:
ret = ret*10 + ord(c) - 48
if minus:
ret *= -1
return ret
# Converts given datetime in tzone to EST. dt = 'yyyymmdd' and tm = 'hh:mm:ss'
def convert2EST(dt, tm, tzone):
y = toInt(dt[0:4])
m = toInt(dt[4:6])
d = toInt(dt[6:8])
hh = toInt(tm[0:2])
mm = toInt(tm[3:5])
ss = toInt(tm[6:8])
# EST timezone and given timezone
est_tz = timezone('US/Eastern')
given_tz = timezone(tzone)
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
# Initialize given datetime and convert it to local/given timezone
local = datetime(y, m, d, hh, mm, ss)
local_dt = given_tz.localize(local)
est_dt = est_tz.normalize(local_dt.astimezone(est_tz))
dt = est_dt.strftime(fmt)
print dt
return dt
Run Code Online (Sandbox Code Playgroud)
当我用convert2EST('20110220','11:00:00','America/Sao_Paulo')调用此方法时
输出为'2011-02-20 08:00:00 EST-0500',但巴西的DST于2月20日结束,正确答案应为'2011-02-20 09:00:00 EST-0500'.
从一些实验中我发现,根据pytz,巴西的DST于2月27日结束,这是不正确的.
pytz是否包含错误数据或我遗漏了什么.任何帮助或评论将不胜感激.
首先是疯狂的实施:
import datetime
import pytz
EST = pytz.timezone('US/Eastern')
def convert2EST(date, time, tzone):
dt = datetime.datetime.strptime(date+time, '%Y%m%d%H:%M:%S')
tz = pytz.timezone(tzone)
dt = tz.localize(dt)
return dt.astimezone(EST)
Run Code Online (Sandbox Code Playgroud)
现在,我们试着称之为:
>>> print convert2EST('20110220', '11:00:00', 'America/Sao_Paulo')
2011-02-20 09:00:00-05:00
Run Code Online (Sandbox Code Playgroud)
如我们所见,我们得到了正确的答案.
更新:我明白了!
巴西在2008年改变了它的夏令时.目前还不清楚它是什么,但可能你的数据已经过时了.
这可能不是pytz错误,因为pytz能够使用您的操作系统数据库.您可能需要更新操作系统.这是(我猜)我得到正确答案的原因,即使使用2005年的pytz,它也使用了我操作系统中的(更新的)数据.