Ray
Ray

Reputation: 8573

Error filling in empty Numpy array with `np.datetime64` objects

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?

Upvotes: 1

Views: 819

Answers (1)

unutbu
unutbu

Reputation: 879501

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.

Upvotes: 3

Related Questions