pandas.to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False, utc=None, format=None, exact=True, unit=None, infer_datetime_format=False, origin='unix', cache=True)
將參數轉換為日期時間
DataFrame.astype
將參數轉換為指定的 dtype。
to_timedelta
將參數轉換為 timedelta。
convert_dtypes
轉換數據類型。
例子 從 DataFrame 的多列組裝日期時間。鍵可以是常見的縮寫,如 ['year', 'month', 'day', 'minute', 'second', 'ms', 'us', 'ns']) 或相同的複數形式 - df = pd.DataFrame({'year': [2015, 2016],
- 'month': [2, 3],
- 'day': [4, 5]})
- pd.to_datetime(df)
- 0 2015-02-04
- 1 2016-03-05
- dtype: datetime64[ns]
複製代碼如果日期不符合[color=rgba(var(--pst-color-link),1)]時間戳限制,則傳遞 errors='ignore' 將返回原始輸入而不是引發任何異常。
除了強制將非日期(或不可解析的日期)強制為 NaT 之外,傳遞 errors='coerce' 將強制將越界日期強制為 NaT。 - pd.to_datetime('13000101', format='%Y%m%d', errors='ignore')
- datetime.datetime(1300, 1, 1, 0, 0)
- pd.to_datetime('13000101', format='%Y%m%d', errors='coerce')
- NaT
複製代碼
傳遞 infer_datetime_format=True 通常可以加速解析,如果它不是完全 ISO8601 格式,而是常規格式。
- s = pd.Series(['3/11/2000', '3/12/2000', '3/13/2000'] * 1000)
- s.head()
- 0 3/11/2000
- 1 3/12/2000
- 2 3/13/2000
- 3 3/11/2000
- 4 3/12/2000
- dtype: object
複製代碼- %timeit pd.to_datetime(s, infer_datetime_format=True)
- 100 loops, best of 3: 10.4 ms per loop
複製代碼- %timeit pd.to_datetime(s, infer_datetime_format=False)
- 1 loop, best of 3: 471 ms per loop
複製代碼
使用 timestamp時間戳記
- pd.to_datetime(1490195805, unit='s')
- Timestamp('2017-03-22 15:16:45')
- pd.to_datetime(1490195805433502912, unit='ns')
- Timestamp('2017-03-22 15:16:45.433502912')
複製代碼對於 float arg,可能會發生精確舍入。為了防止意外行為,請使用固定寬度的精確類型。
使用非 timestamp時間戳記
- pd.to_datetime([1, 2, 3], unit='D',origin=pd.Timestamp('1960-01-01'))
- DatetimeIndex(['1960-01-02', '1960-01-03', '1960-01-04'],dtype='datetime64[ns]', freq=None)
複製代碼
如果輸入是類似列表的並且輸入的元素是混合時區,則如果 utc=False,則返回對像類型為 Index。
- pd.to_datetime(['2018-10-26 12:00 -0530', '2018-10-26 12:00 -0500'])
- Index([2018-10-26 12:00:00-05:30, 2018-10-26 12:00:00-05:00], dtype='object')
複製代碼- pd.to_datetime(['2018-10-26 12:00 -0530', '2018-10-26 12:00 -0500'],
- utc=True)
- DatetimeIndex(['2018-10-26 17:30:00+00:00', '2018-10-26 17:00:00+00:00'],
- dtype='datetime64[ns, UTC]', freq=None)
複製代碼
原文文章
|