0

I need to fill an array with dates, starting from period 2021-07-15 for 120 periods with monthly frequency. currently I use code :

dates= []
for i in range (0, len(output)):
   if (i%120 == 0):
      for e in[d.strftime("%Y-%m-%d") for d in pd.date_range(start='2021-7-1', periods=120, 
         freq='MS').shift(14,freq='D')]:
         dates.append(e)

This code works no problem, but I would like to use numpy as it usually faster then pandas or list. Does anybody know how can I replace this code using numpy datetime64?

1 Answer 1

1

arange can work with datetime64 objects:

In [35]: stop=start+np.timedelta64(120)
In [36]: arr=np.arange(start,stop)
In [37]: arr.shape
Out[37]: (120,)
In [38]: arr[:10]
Out[38]: 
array(['2021-07-15', '2021-07-16', '2021-07-17', '2021-07-18',
       '2021-07-19', '2021-07-20', '2021-07-21', '2021-07-22',
       '2021-07-23', '2021-07-24'], dtype='datetime64[D]')
In [39]: arr[::10]
Out[39]: 
array(['2021-07-15', '2021-07-25', '2021-08-04', '2021-08-14',
       '2021-08-24', '2021-09-03', '2021-09-13', '2021-09-23',
       '2021-10-03', '2021-10-13', '2021-10-23', '2021-11-02'],
      dtype='datetime64[D]')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.