将 numpy.datetime64 转换为 int 时出错

Error when converting numpy.datetime64 to int

我正在尝试通过 int(np.datetime64(...)) 将 np.datetime64 转换为 int。令人惊讶的是,有时它有效,有时它不取决于 datetime 的创建方式:

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

将得到 int:

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

这些日期在 numpy 内部存储的方式有什么不同,然后在转换为 int 时导致错误吗?

尝试:

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

区别在于是否包含时、分、秒等时间值。

当您尝试将日期时间(或np.datetime64)转换为int(或np.int64)时,该值将是epoch time,这是秒的值从 1970-01-01 00:00:00 (utc).

(参见纪元时间计算器:https://www.epochconverter.com/

但是,如果您尝试将“2017-09-26”转换为 int,则很难计算出距 1970-01-01 多少秒 00:00:00,因为该值不包括小时、分钟、秒信息和时区信息。

要使其可转换,您必须添加时间信息,如下:

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

此外,当您的值保存为datetime64时,请使用astype(np.int64)而不是astype(int)将其转换为精确的纪元时间。如果您使用 int,这将 return 从 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
  • 根据@FObersteiner 的评论进行编辑,谢谢!