Reputation: 407
I'm wondering how I can make these three statements a single statement that I loop through:
minute_dt_array = np.arange(start, end, dt.timedelta(minutes=1)).astype(dt.datetime)
hour_dt_array = np.arange(start, end, dt.timedelta(hours=1)).astype(dt.datetime)
day_dt_array = np.arange(start, end, dt.timedelta(days=1)).astype(dt.datetime)
If I want to create a list that is [minutes, days, hours] so I can iterate through a single statement as opposed to writing it three times. How do I do that?
for example, I'm looking to write a loop that does something like this:
timeunits = ['day','hour','minute']
for interval in timeunits:
arrays['%s_array' % interval] = np.arange(start, end, dt.timedelta(**interval**=1)).astype(dt.datetime)
But I don't know what to put in the time delta function.
Upvotes: 0
Views: 216
Reputation: 25544
If you want to be able to call the array by name, what about a zip
to fill a dict
?
from datetime import datetime, timedelta
import numpy as np
start, end = datetime(2020,11,20), datetime(2020,11,22)
arrays = dict()
for k, i in zip(('days','hours','minutes'), (1, 1/24, 1/1440)):
arrays[k] = np.arange(start, end, timedelta(i)).astype(datetime)
# one-liner:
# arrays = {k: np.arange(start, end, timedelta(i)).astype(datetime) for k, i in zip(('days','hours','minutes'), (1, 1/24, 1/1440))}
Or if it is sufficient that arrays
is a list
, simply iterate the time intervals as
arrays = []
for i in (1, 1/24, 1/1440):
arrays.append(np.arange(start, end, timedelta(i)).astype(datetime))
Upvotes: 1
Reputation: 16620
There is no need to do that as with your intervals:
1d = 24h = 1440 minutes
So, every 60minutes you have 1h, every 24hrs you get 1d.
When you combine intervals as you suggest you get duplicate data points for for 1h timedelta resolution, and even triples for daily resolution. So, it should be enough to use the first granularity and just check if you got a round number of minutes, hours:
minute_dt_array = np.arange(start, end, dt.timedelta(minutes=1)).astype(dt.datetime)
the_list = []
for n, dtt in enumerate(minute_dt_array):
the_list.append([n // 1440, n // 60, n]) # days, hours, minutes
the_list
is what you need.
Upvotes: 1