Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datetime intervals with numpy.arange

Tags:

python

numpy

I'd like to create monthly intervals without iterating using np.arange. As a simple example, I'd like an array containing a np.datetime64 object representing New Years Day for the range 1990-2000. I'd think something like:

np.arange(np.datetime64("1990-01-01"), np.datetime64("2000-01-01"), np.timedelta64(1, 'M'), dtype='datetime64[D]')

but this raises the error

TypeError: Cannot cast NumPy timedelta64 scalar from metadata [M] to [D] according to the rule 'same_kind'

If I switch dtype to datetime[M] I get an array of the months, but of course I want the day.

like image 244
triphook Avatar asked Jun 10 '26 16:06

triphook


1 Answers

You can set the original dtype to datetime64[Y] and then cast it to datetime64[D] with .astype()

np.arange(np.datetime64("1990-01-01"), np.datetime64("2000-01-01"), np.timedelta64(1, 'Y'), dtype='datetime64[Y]').astype('datetime64[D]')
like image 155
wpercy Avatar answered Jun 13 '26 07:06

wpercy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!