天天看點

python時間序列資料分析,Python資料分析之時間序列

Python資料分析之時間序列

釋出時間:2020-07-10 06:56:27

來源:51CTO

閱讀:808

作者:up4ever

1. 時間序列類型

時間戳(timestramp)

即特定的時刻

固定時期(period)

如2018年1月或2018年1月1日

時間間隔(interval)

由起始和結束時間戳表示

2. Python處理子產品

Python标準庫包含用于日期和時間資料的資料類型,主要用到datetime、time、calendar子產品。

datetime子產品常使用datetime和timedelta兩種執行個體方法

datetime:以毫秒形式存儲日期和時間

timedelta:表示兩個datetime對象的時間差

引入datetime子產品

import datetime

生成datetime對象

start_date = datetime(2018,1,1)

print(type(start_date))

end_date = datetime(2018,12,31)

print(type(end_date))

delta_date = end_date - start_date

print(type(delta_date))

python時間序列資料分析,Python資料分析之時間序列

字元串轉化datetime對象

datetime.strptime()

date_str = '2018-1-1'

date_strptime = datetime.strptime(date_str, '%Y-%m-%d')

print(type(date_strptime))

print(date_strptime)

python時間序列資料分析,Python資料分析之時間序列

dateutil.parser.parse()

date_str2 = '1-1-2018'

date_parse = parse(date_str2)

print(type(date_parse))

print(date_parse)

python時間序列資料分析,Python資料分析之時間序列

pandas.to_datetime()

date_arr = ['1/1/2018','12/31/2018']

date_todatetime = pd.to_datetime(date_arr)

print(type(date_todatetime))

print(date_todatetime)

python時間序列資料分析,Python資料分析之時間序列

datetime對象轉化字元串

str

start_date = datetime(2018,1,1)

str_start_date = str(start_date)

print(type(str_start_date))

print(str_start_date)

python時間序列資料分析,Python資料分析之時間序列

strftime

start_date = datetime(2018,1,1)

strftime_start_date = start_date.strftime('%Y-%m-%d')

print(type(strftime_start_date))

print(strftime_start_date)

python時間序列資料分析,Python資料分析之時間序列

3. Pandas 時間處理

serial

ts = pd.Series(np.random.randn(6), index=date_list)

print(type(ts))

print(ts)

python時間序列資料分析,Python資料分析之時間序列

date_range()

dates = pd.date_range('2018-1-1', periods=5, freq='W-SAT')

print(dates)

print(pd.Series(np.random.randn(5), index=dates))

python時間序列資料分析,Python資料分析之時間序列

date_index = pd.date_range('2018/1/1', '2018/2/1')

print(date_index)

python時間序列資料分析,Python資料分析之時間序列

移動資料

ts = pd.Series(np.random.randn(5), index=pd.date_range('20180101', periods=5, freq='W-SAT'))

print(ts)

python時間序列資料分析,Python資料分析之時間序列

print(ts.shift(1))

python時間序列資料分析,Python資料分析之時間序列

print(ts.shift(-1))

python時間序列資料分析,Python資料分析之時間序列