I am writing a module that calculates the half hour trading period in a given day. The trading periods start on the half hour and are consecutively numbered from 1 (starting 00:00) to 48 (starting 23:30). Normally there are 48 trading periods in a day, but on the day that daylight savings starts there are 46 and on the day it ends there are 50.
The code below works on all 'normal' days, but fails to give correct trading period numbers on days when daylight savings starts or ends because datetime.replace()
in the code below uses the same UTC
time offset for the start of the day. On days when daylight savings changes this assumption is incorrect.
Is it possible for datetime.replace() to set the time at 00:00 for 'wall clock' time, so that the time difference matches what you get if you set a stopwatch at 00:00 then counted the number of half hour intervals it would match correctly for all days? I have not found an automatic way to do this.
An example:
Daylight savings ended in New Zealand on 5th April 2015 at 03:00 (2015-05-04 14:00Z
). Therefore the hour 02:00-02:59 (2015-05-04 14:00Z
- 2015-05-04 14:59Z
) was repeated in 'wall clock' time. Therefore in New Zealand it took 18000 seconds to reach 4am on the 5th April 2015, as daylight savings time ended. On 28th September 2014 it took 10800 seconds, as daylight savings time started.
@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))