時間字符串與時間戳批量轉換
import pandas as pd
import datetime as dt
import time
df = pd.DataFrame(data= ['2019-01-01','2019-01-02','2019-01-03','2019-01-04','2019-01-05','2019-01-06','2019-01-07','2019-01-08'], index=range(0,8), columns=['date'])
#將時間字符序列轉化爲時間戳
y = df['date'].apply(lambda x: time.mktime(dt.datetime(int(x.split('-')[0]),int(x.split('-')[1]),int(x.split('-')[2]),0,0,0).timetuple()))
print('列表式時間字符轉化爲時間戳:','\n',y)
#將時間戳序列轉化爲時間字符
y1 = y.apply(lambda x:time.strftime('%Y-%m-%d',time.localtime(x)))
print('列表式時間戳轉化爲時間字符:','\n',y1)
結果輸出:
列表式時間字符轉化爲時間戳:
0 1.546272e+09
1 1.546358e+09
2 1.546445e+09
3 1.546531e+09
4 1.546618e+09
5 1.546704e+09
6 1.546790e+09
7 1.546877e+09
Name: date, dtype: float64
列表式時間戳轉化爲時間字符:
0 2019-01-01
1 2019-01-02
2 2019-01-03
3 2019-01-04
4 2019-01-05
5 2019-01-06
6 2019-01-07
7 2019-01-08
Name: date, dtype: object