1. 程式人生 > >【python】numpy.datetime64( ) 時間和 datetime.datetime 互轉

【python】numpy.datetime64( ) 時間和 datetime.datetime 互轉

首先定義幾個時間變數datetime、Timestamp、numpy.datetime64:

import datetime
import numpy as np
import pandas as pd
dt = datetime.datetime(2018, 9, 1)
# A strange way to extract a Timestamp object, there's surely a better way?
ts = pd.DatetimeIndex([dt])[0]
dt64 = np.datetime64(dt)

dt
Out[67]: datetime.datetime(2018
, 9, 1, 0, 0) ts Out[68]: Timestamp('2018-09-01 00:00:00') dt64 Out[69]: numpy.datetime64('2018-09-01T00:00:00.000000')

轉換numpy.datetime64物件

1、直接用astype的方法進行轉化
dt64.astype(datetime.datetime)
Out[74]: datetime.datetime(2018, 9, 1, 0, 0)
2、先轉化為timestamp,再轉化為datetime
  • 先轉化為timestamp:
(dt64-np.datetime64('1970-01-01T00:00:00Z'
)) / np.timedelta64(1, 's') Out[72]: 1535760000.0
  • 再將timestamp轉為datetime格式
datetime.datetime.fromtimestamp((dt64-np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 's'))
Out[76]: datetime.datetime(2018, 9, 1, 8, 0)