📅  最后修改于: 2020-10-29 04:46:38             🧑  作者: Mango
Pandas 可以提供与所有域的时间序列数据一起使用的功能。它还使用NumPy datetime64和timedelta64 dtypes合并了其他Python库中的大量功能,例如scikits.timeseries。它提供了用于处理时间序列数据的新功能。
时间序列工具对于数据科学应用程序最有用,并且可以处理Python使用的其他软件包。
import pandas as pd
# Create the dates with frequency
info = pd.date_range('5/4/2013', periods = 8, freq ='S')
info
输出:
DatetimeIndex(['2013-05-04 00:00:00', '2013-05-04 00:00:01',
'2013-05-04 00:00:02', '2013-05-04 00:00:03',
'2013-05-04 00:00:04', '2013-05-04 00:00:05',
'2013-05-04 00:00:06', '2013-05-04 00:00:07'],
dtype='datetime64[ns]', freq='S')
info = pd.DataFrame({'year': [2014, 2012],
'month': [5, 7],
'day': [20, 17]})
pd.to_datetime(info)
0 2014-05-20
1 2012-07-17
dtype: datetime64[ns]
如果日期不符合时间戳,则可以传递errors =’ignore’。它将返回原始输入而不会引发任何异常。
如果您通过errors =’coerce’,它将对NaT强制执行越界日期。
import pandas as pd
pd.to_datetime('18000706', format='%Y%m%d', errors='ignore')
datetime.datetime(1800, 7, 6, 0, 0)
pd.to_datetime('18000706', format='%Y%m%d', errors='coerce')
输出:
Timestamp('1800-07-06 00:00:00')
import pandas as pd
dmy = pd.date_range('2017-06-04', periods=5, freq='S')
dmy
输出:
DatetimeIndex(['2017-06-04 00:00:00',
'2017-06-04 00:00:01',
'2017-06-04 00:00:02',
'2017-06-04 00:00:03',
'2017-06-04 00:00:04'],
dtype='datetime64[ns]', freq='S')
import pandas as pd
dmy = dmy.tz_localize('UTC')
dmy
输出:
DatetimeIndex(['2017-06-04 00:00:00+00:00', '2017-06-04 00:00:01+00:00',
'2017-06-04 00:00:02+00:00',
'2017-06-04 00:00:03+00:00',
'2017-06-04 00:00:04+00:00'],
dtype='datetime64[ns, UTC]', freq='S')
import pandas as pd
dmy = pd.date_range('2017-06-04', periods=5, freq='S')
dmy
输出:
DatetimeIndex(['2017-06-04 00:00:00', '2017-06-04 00:00:01',
'2017-06-04 00:00:02', '2017-06-04 00:00:03',
'2017-06-04 00:00:04'],
dtype='datetime64[ns]', freq='S')