我正在嘗試通過 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)
將導致int:
1506439211546205184
TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.date'
這些日期在 numpy 內部存盤的方式是否存在差異,然后在轉換為 int 時會導致錯誤?
uj5u.com熱心網友回復:
區別在于它是否包含時間值,例如小時、分鐘和秒。
當您嘗試將 datetime (or np.datetime64) 轉換為int(or 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 的評論,謝謝!
uj5u.com熱心網友回復:
嘗試:
a = np.datetime64('2017-09-26','us').astype(np.int64)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/429343.html
下一篇:在R時間框架索引中滾動應用
