python - 将 numpy.datetime64 转换为 int 时出错

标签 python numpy datetime python-datetime

我正在尝试通过 int(np.datetime64(...)) 将 np.datetime64 转换为 int。令人惊讶的是,有时它有效,有时则不起作用,具体取决于日期时间的创建方式:

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

将结果整数:

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

这些日期在 numpy 内部存储的方式是否存在差异,然后在转换为 int 时导致错误?

最佳答案

区别在于它是否包含时间值,例如小时、分钟和秒。

当您尝试将日期时间(或 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

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

关于python - 将 numpy.datetime64 转换为 int 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71174053/

相关文章:

python - 计算python中多维数组中数组的出现次数

json - Flask 前端具有 Tensorflow 但不具有 Tensorflow 服务

c# - SetSystemTime - UTC 或本地时间?

python - 转置 pandas 数据框并垂直 append

python - 如何限制 tkinter 列表框中的选择数量?

python - 在 Pycharm 中切换运行模式和 Debug模式

python - 如何解决 Python 中的函数逼近任务?

python - 在每个页面上搜索输入。 Django

ios - NSDate:将 UTC 值转换为军事时区值

php - 计算 PHP 中不包括周末和时间段的时间差(以秒为单位)