Python:鉴于当前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

解决方法:

我相信你得到这个结果是因为你增加了一天而不是86400秒.天与秒之间没有统一的,始终正确的等价.例如,如果pytz强制一天“真正”为86400秒,那么将一天添加到12月31日或6月30日有时会导致结果的秒字段“一秒钟关闭”,因为在某些情况下那些日子已经有86401秒了. (未来可能会有86402甚至86399秒.)

因此,添加一天意味着简单地将日期递增1,如果需要,可以延续到月份和年份,但不会更改时间字段.尝试添加86400秒,看看是否得到了想要的结果.

上一篇:PHP的DST处理时区


下一篇:python – pytz – 将UTC和时区转换为本地时间