解析来自各种来源和格式的时间序列信息
pd.to_datetime(
arg,#int, float, str, datetime, list, tuple, 1-d array, Series DataFrame/dict-like
errors='raise',# {'ignore', 'raise', 'coerce'}, default 'raise'
dayfirst=False,
yearfirst=False,
utc=None,
format=None,#格式,比如 "%d/%m/%Y"
exact=True,
unit=None,#单位str, default 'ns',可以是(D,s,ms,us,ns)
infer_datetime_format=False,
origin='unix',#指定从什么时间开始,默认为19700101
cache=True,
)
pd.to_datetime()
import datetime
import pandas as pd
import numpy as np
dti = pd.to_datetime(['1/1/2018', np.datetime64('2018-01-01'),
datetime.datetime(2018, 1, 1)])
dti
DatetimeIndex([‘2018-01-01’, ‘2018-01-01’, ‘2018-01-01’], dtype=‘datetime64[ns]’, freq=None)
pd.to_datetime(['2020-04-20', '20/04/2020','Apr 20 2020'])
DatetimeIndex([‘2020-04-20’, ‘2020-04-20’, ‘2020-04-20’], dtype=‘datetime64[ns]’, freq=None)
import time
time.asctime()
‘Tue Apr 7 21:50:17 2020’
pd.to_datetime(time.asctime())
Timestamp(‘2020-04-07 21:50:17’)
还有更加偷懒的办法,假如整理数据时遇到了大量的时间需要输入,比如2020-11-11 00:00:00,输入-和:太浪费时间了,而且时间之间没有什么变化规律可循,这种情况下可以直接输入20201111000000进行记录,之后再借助pd.to_datetime()解析,省时省力一步到位。
pd.to_datetime('20201111000000')
Timestamp(‘2020-11-11 00:00:00’)
pd.to_datetime('2020/12/12', format='%Y/%m/%d')
Timestamp(‘2020-12-12 00:00:00’)
pd.to_datetime('12-11-2010 00:00', format='%d-%m-%Y %H:%M')
Timestamp(‘2010-11-12 00:00:00’)
df = pd.DataFrame({'year': [2015, 2016],
....: 'month': [2, 3],
....: 'day': [4, 5],
....: 'hour': [2, 3]})
df
year month day hour
0 2015 2 4 2
1 2016 3 5 3
pd.to_datetime(df)
0 2015-02-04 02:00:00
1 2016-03-05 03:00:00
dtype: datetime64[ns]
pd.to_datetime(df[['year','month','day']])
0 2015-02-04
1 2016-03-05
dtype: datetime64[ns]
pd.to_datetime(['2009/07/31', 'asd'], errors='ignore')
Index([‘2009/07/31’, ‘asd’], dtype=‘object’)
pd.to_datetime(['2009/07/31', 'asd'], errors='raise')
ParserError: Unknown string format: asd
pd.to_datetime(['2009/07/31', 'asd'], errors='coerce')
DatetimeIndex([‘2009-07-31’, ‘NaT’], dtype=‘datetime64[ns]’, freq=None)
指定时间
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)
不指定时间则默认从19700101开始
pd.to_datetime([1, 2, 3], unit='D')
DatetimeIndex([‘1970-01-02’, ‘1970-01-03’, ‘1970-01-04’], dtype=‘datetime64[ns]’, freq=None)