I'm pretty new to python so I need some help. The below code gets the job done, but I feel like it isn't the most efficient way to accomplish this, any input would be greatly appreciated.
The goal: 1) pass a string start and end date 2) create a list to be able to chunk a request to an API. Each end date need to be 4 hours after the start date 3) each following start date in the list needs to be 3 hours after the previous start date 4) end the list when the final start date is >= end date
Important the final number must come out as i.e. '2018-06-05T09 2018-06-05T13' or my API request won't work
Thank you all in advance!
from datetime import datetime, timedelta
import numpy as np
start='2018-06-05T00'
end='2020-11-01T23'
start_date = datetime.strptime(start, '%Y-%m-%dT%H')
end_date = datetime.strptime(end, '%Y-%m-%dT%H')
delta = timedelta(hours=3)
end_date_initial = start_date timedelta(hours=4)
start_date_list = [start_date]
end_date_list = [end_date_initial]
while True:
start_date = delta
start_date_list.append(start_date)
if start_date >= end_date:
break
while True:
end_date_initial = delta
end_date_list.append(end_date_initial)
if end_date_initial >= end_date:
break
start_date_array = np.array(start_date_list)
end_date_array = np.array(end_date_list)
formated_start_date = []
formated_end_date = []
for i in range(len(start_date_array)):
formated_start_date.append(start_date_array[i].strftime('%Y-%m-%dT%H'))
for i in range(len(end_date_array)):
formated_end_date.append(end_date_array[i].strftime('%Y-%m-%dT%H'))
# print(start_date_array[0], end_date_array[0])
# print(formated_start_date[0], formated_end_date[0])
time = formated_start_date[0] ' ' formated_end_date[0]
def listOfTuples(i, j):
return list(map(lambda x, y:(x ' ' y), i, j))
time_tuples = listOfTuples(formated_start_date, formated_end_date)
print(time_tuples[3])
CodePudding user response:
If I've understood correctly, you can do this pretty easily and still take advantage of numpy's vectorization and broadcasting capabilities:
import numpy as np
ti, tf = np.datetime64("2018-06-05T00"), np.datetime64("2020-11-01T23")
start = np.arange(ti, tf, np.timedelta64(3, "h"))
end = start np.timedelta64(4, "h")
api_times = [" ".join(map(str, t)) for t in zip(start, end)]