from datetime import datetime, timedelta
import pytz
from copy import deepcopy
def round_dt(dt, dir, amount):
new_minute = (dt.minute // amount + dir) * amount
return dt + timedelta(minutes = new_minute - dt.minute)
events=[
{'start': {'dateTime': '2022-03-03T07:00:00-08:00', 'timeZone': 'America/Vancouver'},
'end': {'dateTime': '2022-03-03T07:01:00-08:00', 'timeZone': 'America/Vancouver'}
},
{'start': {'dateTime': '2022-03-03T07:31:00-08:00', 'timeZone': 'America/Vancouver'},
'end': {'dateTime': '2022-03-03T07:32:00-08:00', 'timeZone': 'America/Vancouver'}
}
]
res=[]
for e in events:
new_start_time = datetime.strptime(e['start']['dateTime'], '%Y-%m-%dT%H:%M:%S%z')
new_end_time = datetime.strptime(e['end']['dateTime'], '%Y-%m-%dT%H:%M:%S%z')
converted_start_time = round_dt(new_start_time,0,30)
converted_end_time = round_dt(new_end_time,1,30)
time_dif = converted_end_time-converted_start_time
print(converted_start_time,converted_end_time,time_dif)
minute_dif = int(round(time_dif.total_seconds()/60, 0))
half_hours = (minute_dif//30)
print(minute_dif,half_hours)
for delta in range(0,30*half_hours,30):
time_slots = dict(deepcopy(e))
start = new_start_time + timedelta(minutes=delta)
end = new_start_time + timedelta(minutes=(delta+30))
time_slots['start']['dateTime'] = start.strftime('%Y-%m-%dT%H:%M:%S%z')
time_slots['end']['dateTime'] = end.strftime('%Y-%m-%dT%H:%M:%S%z')
res.append(time_slots)
print("----------")
print(res)
I have an issue where after rounding start time down to a 30 min interval and rounding up end time to 30 min intervals. When adding to that value I get the time to be 8:01 instead of 8:00.
Expect results of start times when 7:(<30)->7:00 when 7:(>30)->7:30 when end times are 7:(<30)->7:30 and when 7:(>30)->8:00.
Problem area is in the for loop and adding to the start tine produces 8:01 instead of 8:00.
ā
2022-03-03 07:00:00-08:00 2022-03-03 07:30:00-08:00 0:30:00
30 1
2022-03-03 07:30:00-08:00 2022-03-03 08:00:00-08:00 0:30:00
30 1
----------
[{'start': {'dateTime': '2022-03-03T07:00:00-0800', 'timeZone': 'America/Vancouver'}, 'end': {'dateTime': '2022-03-03T07:30:00-0800', 'timeZone': 'America/Vancouver'}}, {'start': {'dateTime': '2022-03-03T07:31:00-0800', 'timeZone': 'America/Vancouver'}, 'end': {'dateTime': '2022-03-03T08:01:00-0800', 'timeZone': 'America/Vancouver'}}]