1. 程式人生 > >利用python處理時間戳

利用python處理時間戳

拿這個表(此表為2018年深圳杯D題源資料)舉例子,'a'這一列是時間戳,為了資料處理的方便,把時間戳給分成年,月,日,時,秒。
程式碼實現如下:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: Alpha Labs


if __name__ == '__main__':
    from datetime import datetime
    import pandas as pd
    import numpy as np
    import time

    path = 'time_un_processed.csv'
    df = pd.read_csv(path)
    a = df['a']   # a 這一列是時間戳
    b = [time.gmtime(i) for i in a]  #time.gmtime() 接收時間戳(1970紀元後經過的浮點秒數)並返回格林威治天文時間下的時間元組t。注:t.tm_isdst始終為0
    Y = [] 
    M = []
    D = []
    H = []
    MIN = []
    S = []
    for i in b:
        a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8, a_9 = i
        Y.append(a_1)
        M.append(a_2)
        D.append(a_3)
        H.append(a_4)
        MIN.append(a_5)
        S.append(a_6)

    S_Y = pd.Series(Y, name='Year')
    S_M = pd.Series(M, name='Month')
    S_D = pd.Series(D, name='Day')
    S_H = pd.Series(H, name='Hour')
    S_MIN = pd.Series(MIN, name='Minute')
    S_S = pd.Series(S, name='s')

    time_df = pd.concat([df, S_Y, S_M, S_D, S_H, S_MIN, S_S], axis=1)
    print(time_df.head())
    path_2 = './time_processed.csv'

    time_df.to_csv(path_2)


轉化後的csv表格為: