Home > Back-end >  another question about Python/Numpy datetimes
another question about Python/Numpy datetimes

Time:11-12

Hi I am trying to read some date info from Excel using openpyxl which returns them as datetime.datetime. I need to resample the data and then plot the resampled times using maplotlib. I would like an array of dates starting at tmin, incremented by 30.0 days. The code stub is

import numpy as np
import datetime

vals = [
datetime.date.fromisoformat('2004-06-01'),
datetime.date.fromisoformat('2004-07-01'),
datetime.date.fromisoformat('2004-08-01'),
datetime.date.fromisoformat('2004-09-01'),
datetime.date.fromisoformat('2004-10-01'),
datetime.date.fromisoformat('2004-11-01')]

xtim = np.array(vals)
tmin = np.min(xtim)

ytim = np.arange(0.0, 150.0, 30.0)
tnew = tmin   ytim.astype('timedelta64[D]')

Unfortunately this gives me the error message UFuncTypeError: ufunc 'add' cannot use operands with types dtype('O') and dtype('<m8[D]'). I have to say using numpy and Python datetimes is a complete mystery to me. - I can usually kludge things to make them work but not in this case. All suggestions gratefully received - thanks!

CodePudding user response:

You should wrap tmin in an array with 'datetime64' type:

np.array(tmin, dtype='datetime64')   ytim.astype('timedelta64[D]')

output: array(['2004-06-01', '2004-07-01', '2004-07-31', '2004-08-30', '2004-09-29'], dtype='datetime64[D]')

CodePudding user response:

To add 30 days I'd suggest using datetime.timedelta(days=30).
For example as:

import numpy as np
import datetime

vals = [
    datetime.date.fromisoformat('2004-06-01'),
    datetime.date.fromisoformat('2004-07-01'),
    datetime.date.fromisoformat('2004-08-01'),
    datetime.date.fromisoformat('2004-09-01'),
    datetime.date.fromisoformat('2004-10-01'),
    datetime.date.fromisoformat('2004-11-01')]

xtim = np.array(vals)
tmin = np.min(xtim)


t_new=[tmin datetime.timedelta(days=i) for i in np.arange(0.0, 150.0, 30.0)] 
  • Related