Nic*_*eld 5 python timezone datetime utc
我在玩 Google App Engine,我了解到时区固定为 UTC。我想确定用户本地时区当天的开始和结束时间。所以基本上,给定 UTC 的当前时间,您如何确定当天的开始和结束时间,同时考虑到夏令时转换。
我有一些笨重的示例代码。请注意,我意识到如果我手动指定日期,我也可以指定明天的日期,但它们是示例,我想以编程方式确定它。我的主要问题是,如果我将 timedelta 添加到带有时区的日期时间,然后对其进行标准化(就像 pytz 文档中所建议的那样),我会得到一个日期时间,在夏令时切换期间关闭一小时。
代码中没有提到,但最终目的是将这些时间转换回 UTC,这就是为什么了解时区很重要的原因。
#!/usr/bin/python
import datetime
from pytz.gae import pytz
hobart_tz = pytz.timezone('Australia/Hobart')
utc_dt = pytz.utc.localize(datetime.datetime.utcnow())
hobart_dt = utc_dt.astimezone(hobart_tz)
# create a new datetime for the start of the day and add a day to it to get tomorrow.
today_start = datetime.datetime(hobart_dt.year, hobart_dt.month, hobart_dt.day)
today_start = hobart_tz.localize(today_start)
today_end = hobart_tz.normalize(today_start + datetime.timedelta(days=1))
print 'today:', today_start
print ' next:', today_end
print
# gives:
# today: 2011-08-28 00:00:00+10:00
# next: 2011-08-29 00:00:00+10:00
# but say today is a daylight savings changeover.
# after normalisation, we are off by an hour.
dst_finish_2011 = datetime.datetime(2011, 4, 3) # this would come from hobart_dt
dst_finish_2011 = hobart_tz.localize(dst_finish_2011)
next = hobart_tz.normalize(dst_finish_2011 + datetime.timedelta(days=1))
print '2011-04-03:', dst_finish_2011
print '2011-04-04:', next # expect 2011-04-04 00:00:00+10:00
print
# gives
# 2011-04-03: 2011-04-03 00:00:00+11:00
# 2011-04-04: 2011-04-03 23:00:00+10:00 (wrong)
dst_start_2011 = datetime.datetime(2011, 10, 2) # this would come from hobart_dt
dst_start_2011 = hobart_tz.localize(dst_start_2011)
next = hobart_tz.normalize(dst_start_2011 + datetime.timedelta(days=1))
print '2011-10-02:', dst_start_2011
print '2011-10-03:', next # expect 2011-10-03 00:00:00+11:00
print
# gives
# 2011-10-02: 2011-10-02 00:00:00+10:00
# 2011-10-03: 2011-10-03 01:00:00+11:00 (wrong)
# I guess we could ignore the timezone and localise *after* ?
dst_finish_2011 = datetime.datetime(2011, 4, 3) # this would come from hobart_dt
next = dst_finish_2011 + datetime.timedelta(days=1)
# now localise
dst_finish_2011 = hobart_tz.localize(dst_finish_2011)
next = hobart_tz.localize(next)
print '2011-04-03:', dst_finish_2011
print '2011-04-04:', next # expect 2011-04-04 00:00:00+10:00
print
# gives
# 2011-04-03: 2011-04-03 00:00:00+11:00
# 2011-04-04: 2011-04-04 00:00:00+10:00
Run Code Online (Sandbox Code Playgroud)
我相信您得到这个结果是因为您添加了一天而不是 86400 秒。天和秒之间不存在统一、始终正确的等价关系。例如,如果pytz
强制一天“确实”为 86400 秒,则在 12 月 31 日或 6 月 30 日日期中添加一天有时会导致结果的秒字段“减少一秒”,因为在某些年份那些日子已经有86401秒了。(将来他们可能有 86402 甚至 86399 秒。)
因此,添加一天意味着简单地将一天增加一天,如有必要,则延续到月份和年份,但不更改一天中的时间字段。尝试添加 86400 秒,看看是否得到所需的结果。
归档时间: |
|
查看次数: |
3341 次 |
最近记录: |