1

I've always been confused about the interaction between Python's standard library datetime objects and Numpy's datetime objects. The following code gives an error, which baffles me.

from datetime import datetime
import numpy as np

b = np.empty((1,), dtype=np.datetime64)
now = datetime.now()
b[0] = np.datetime64(now)

This gives the following error:

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

What am I doing wrong here?

1 Answer 1

3

np.datetime64 is a class, whereas np.dtype('datetime64[us]') is a NumPy dtype:

import numpy as np
print(type(np.datetime64))
# <class 'type'>

print(type(np.dtype('datetime64[us]')))
# <class 'numpy.dtype'>

Specify the dtype of b using the NumPy dtype, not the class:

from datetime import datetime
import numpy as np

b = np.empty((1,), dtype='datetime64[us]')  
# b = np.empty((1,), dtype=np.dtype('datetime64[us]'))  # also works
now = datetime.now()
b[0] = np.datetime64(now)
print(b)
# ['2019-05-30T08:55:43.111008']

Note that datetime64[us] is just one of a number of possible dtypes. For instance, there are datetime64[ns], datetime64[ms], datetime64[s], datetime64[D], datetime64[Y] dtypes, depending on the desired time resolution.

datetime.dateitem.now() returns a a datetime with microsecond resolution, so I chose datetime64[us] to match.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. That solves my problem. Where can I find an "official" documentation page listing all the datatypes? I couldn't find one. The most obvious place, docs.scipy.org/doc/numpy/reference/arrays.dtypes.html, has only 1 instance of the text "datetime", and it wasn't all that informative.
Googling "numpy datetime64" should lead you to the official docs.

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.