我试图通过int将np.datetime64转换为int(np.datetime64(.))。令人惊讶的是,有时它可以工作,有时它并不取决于日期时间是如何创建的:
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时导致错误,这有区别吗?
发布于 2022-02-18 14:15:33
区别在于它是否包括时间值,例如小时、分钟和秒。
当您尝试将datetime (或np.datetime64)转换为int (或np.int64)时,值将是时代时间,它是从1970-01-01 : 00:00:00 (utc)之间的秒值。
(参见划时代时间计算器:https://www.epochconverter.com/)
但是,如果您尝试将"2017-09-26“转换为int,则很难计算1970-01-01 :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)而不是astype(int)将其转换为精确的时间。如果使用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发布于 2022-02-18 13:49:02
尝试:
a = np.datetime64('2017-09-26','us').astype(np.int64) https://stackoverflow.com/questions/71174053
复制相似问题