Python數據分析之時間序列

1. 時間序列類型

  • 時間戳(timestramp)
    即特定的時刻
  • 固定時期(period)
    如2018年1月或2018年1月1日
  • 時間間隔(interval)
    由起始和結束時間戳表示

2. Python處理模塊

Python標準庫包含用於日期和時間數據的數據類型,主要用到datetime、time、calendar模塊。
datetime模塊常使用datetime和timedelta兩種實例方法dom

  • datetime:以毫秒形式存儲日期和時間
  • timedelta:表示兩個datetime對象的時間差

引入datetime模塊ide

import datetime

生成datetime對象3d

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數據分析之時間序列

字符串轉化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數據分析之時間序列

  • dateutil.parser.parse()
    date_str2 = '1-1-2018'
    date_parse = parse(date_str2)
    print(type(date_parse))
    print(date_parse)

    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數據分析之時間序列

datetime對象轉化字符串

  • strcode

    start_date = datetime(2018,1,1)
    str_start_date = str(start_date)
    print(type(str_start_date))
    print(str_start_date)

    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數據分析之時間序列

3. Pandas 時間處理

  • serial對象

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

    Python數據分析之時間序列

  • date_range()blog

    dates = pd.date_range('2018-1-1', periods=5, freq='W-SAT') 
    print(dates)
    print(pd.Series(np.random.randn(5), index=dates))

    Python數據分析之時間序列

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

    Python數據分析之時間序列

  • 移動數據
    ts = pd.Series(np.random.randn(5), index=pd.date_range('20180101', periods=5, freq='W-SAT'))
    print(ts)

    Python數據分析之時間序列

    print(ts.shift(1))

    Python數據分析之時間序列

    print(ts.shift(-1))

    Python數據分析之時間序列

相關文章
相關標籤/搜索