1

Why numpy started converting date object to datetime64[s] type object in the newer versions ? How to make it backward compatible ?

Example:

Code snippet:

import datetime
import numpy as np

dt = datetime.date(1970, 1, 1)

array = np.array([dt], dtype='datetime64[s]')

array

Result:

**Numpy version 1.12.0**

array(['1970-01-01T00:00:00'], dtype='datetime64[s]')

**Numpy version 1.9.3**

TypeError: Cannot cast datetime.date object from metadata [D] to [s] according to the rule 'same_kind'
2
  • Does this answer help stackoverflow.com/a/37444604/2254228 ? Commented Apr 16, 2017 at 16:15
  • 1
    yeah, sort of. Thanks @CMorris. Commented Apr 17, 2017 at 6:57

1 Answer 1

1

Try a `'D' intermediate:

In [27]: np.array([dt],'datetime64[D]')
Out[27]: array(['1970-01-01'], dtype='datetime64[D]')
In [28]: np.array([dt],'datetime64[D]').astype('datetime64[s]')
Out[28]: array(['1970-01-01T00:00:00'], dtype='datetime64[s]')

Though in my version, the direct creation works:

In [29]: np.array([dt],'datetime64[s]')
Out[29]: array(['1970-01-01T00:00:00'], dtype='datetime64[s]')
In [30]: np.__version__
Out[30]: '1.12.0'
In [31]: dt
Out[31]: datetime.date(1970, 1, 1)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. This works. But then how can I find that the actual unit of dt is 'D' and not 's' ?
Also, It works in newer version for me too. But I want to check whether dt is datetime64[D] compatible or datetime64[s] compatible ? Like datetime.date(1970, 1, 1) is datetime64[D] type compatible but datetime.datetime(1970, 1, 1, 10, 30) is datetime64[s] type compatible.

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.