0

I have a numpy array which contains hours from 4 days:

s = np.array([0.0, 1.0, 2.0, 3.0, 4.0 ....96.0])

I want to create a datetime object from that.

I know that the first element is at timestamp 2021-03-21 00:00, so:

start_date = datetime.datetime.strptime('2021-03-21 00:00', '%Y-%m-%d %H:%M')

How can I create a new array which contains datetimes, incremented by an hour from the s array.

1
  • you can do something like start_date_incremented = [x + datetime.timedelta(hour = 1) for x in start_date_array] Commented Mar 26, 2021 at 12:45

1 Answer 1

1

Use timedelta to build your new array:

>>> import numpy as np
>>> from datetime import datetime, timedelta
>>> s = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 96.0])
>>> start_date = datetime.strptime('2021-03-21 00:00', '%Y-%m-%d %H:%M')
>>> [start_date + timedelta(hours=diff) for diff in s]
[datetime.datetime(2021, 3, 21, 0, 0), datetime.datetime(2021, 3, 21, 1, 0), datetime.datetime(2021, 3, 21, 2, 0), datetime.datetime(2021, 3, 21, 3, 0), datetime.datetime(2021, 3, 21, 4, 0), datetime.datetime(2021, 3, 25, 0, 0)]
Sign up to request clarification or add additional context in comments.

5 Comments

It gives me: unsupported type for timedelta hours component: numpy.float32. The same if I try to convert to integers
Which Python & Numpy version are you using?
np: 1.19.2 , python: 3.7.10
Hm I'm using Numpy 1.13.3 and Python 3.6.9 but shouldn't make a huge difference. You tried hours=int(diff)?
Good to hear! Another option would've been to use int_ to convert to int and then use item to access the Python value, like that: [start_date + timedelta(hours=diff.item()) for diff in np.int_(s)]

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.