【发布时间】:2015-10-20 04:03:14
【问题描述】:
我正在编写一个模块来计算给定一天的半小时交易时间。交易时段从半小时开始,从 1(从 00:00 开始)到 48(从 23:30 开始)连续编号。通常一天有 48 个交易时段,但夏令时开始当天有 46 个,结束当天有 50 个。
下面的代码适用于所有“正常”日期,但无法在夏令时开始或结束的日子给出正确的交易期数,因为下面代码中的 datetime.replace() 使用相同的 UTC 时间偏移作为开始那天。在夏令时改变的日子里,这个假设是不正确的。
datetime.replace() 是否可以将“挂钟”时间设置为 00:00,以便时差与您在 00:00 设置秒表时得到的时间相匹配,然后计算半小时间隔它会在所有日子里正确匹配吗?我还没有找到自动执行此操作的方法。
一个例子:
新西兰的夏令时于 2015 年 4 月 5 日 03:00 (2015-05-04 14:00Z) 结束。因此,小时 02:00-02:59 (2015-05-04 14:00Z - 2015-05-04 14:59Z) 在“挂钟”时间重复。因此,在 2015 年 4 月 5 日,新西兰用了 18000 秒才到达凌晨 4 点,因为夏令时结束了。 2014 年 9 月 28 日,夏令时开始用时 10800 秒。
@staticmethod
def half_hour_from_utc(time_utc = None):
# Get the time as NZ civil time.
time_nz = time_utc.astimezone(pytz.timezone('Pacific/Auckland'))
# Get the time tuple for the start of the day. This is done by keeping
# the date the same but setting the hours, minutes, seconds and
# microseconds to zero.
time_start_of_day = time_nz.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
# Get total number of seconds. The half hour period is the number of
# 1800 second periods that have passed + 1
total_secs = int((time_nz - time_start_of_day).total_seconds())
half_hour = 1 + total_secs // 1800
print('%s %s %s %s\n' % (time_nz, time_start_of_day, total_secs, half_hour))
【问题讨论】: