zlenyk
zlenyk

Reputation: 1000

Error when converting numpy.datetime64 to int

I'm trying to convert np.datetime64 to int via int(np.datetime64(...)). Surprisingly sometimes it works and sometimes it doesn't depending on how was datetime created:

a = np.datetime64('2017-09-26T15:20:11.546205184')
int(a)
a = np.datetime64('2017-09-26')
int(a)

will results int:

1506439211546205184
TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.date'

Is there a difference in how those dates are stored internally by numpy and then causing error when converting to int?

Upvotes: 2

Views: 3267

Answers (2)

Park
Park

Reputation: 2484

The difference is whether it include time values, such as hours, minutes, and seconds.

When you try to convert datetime (or np.datetime64) to int (or np.int64), the value will be epoch time, which is a value of seconds from 1970-01-01 00:00:00 (utc).

(See epoch time calculator: https://www.epochconverter.com/)

However, if you try to convert "2017-09-26" to int, it is hard to calculate how many seconds from 1970-01-01 00:00:00 because the value does not include hour, minutes, seconds information and timezone information.

To make it convertable, you have to add time information, as follows:

a = np.datetime64('2017-09-26T00:00:00.000000000')
print(int(a)) # 1506384000000000000 --> This is an epoch time for 2017-09-26 00:00:00

a = np.datetime64('2017-09-26','us').astype(np.int64) # not int, use np.int64
print(a) # 1506384000000000 -> This is also a epoch time for 2017-09-26 00:00:00

In addition, please use astype(np.int64) instead of astype(int) to convert it to exact epoch time when your value is saved as datetime64. If you use int, this will return the number of days from 1970-01-01.

a = np.datetime64('2017-09-26T15:20:11.546205184').astype(int)
print(a) # 1072585728 -> not an epoch time, but days from 1970-01-01

a = np.datetime64('2017-09-26T15:20:11.546205184').astype(np.int64)
print(a) # 1506439211546205184 -> a correct epoch time of 2017-09-26 15:20:11 with miliseconds
  • edited with consideration of @FObersteiner 's comment, Thanks!

Upvotes: 3

baovolamada
baovolamada

Reputation: 36

Try:

a = np.datetime64('2017-09-26','us').astype(np.int64) 

Upvotes: 1

Related Questions