本文介紹了在 pandas.Series 中將時(shí)間戳轉(zhuǎn)換為 datetime.datetime的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我有熊貓系列,其中索引是整數(shù)列表(時(shí)間戳),我如何將它們轉(zhuǎn)換為 datetime.datetime(帶時(shí)區(qū))比以下原始轉(zhuǎn)換更有效?
I have pandas Series where index is a list of integer (timestamp), how can I convert them to datetime.datetime (with timezone) more efficient than below raw conversion?
pd.Series(data=s.values, index=map(lambda x:datetime.datetime.fromtimestamp(x,tz=utc), s.index))
推薦答案
In [49]: s = Series(range(10))
使用to_datetime
,你可以提供一個(gè)單位來選擇整數(shù)的含義.
Using to_datetime
, you can supply a unit to select what the meaning of the integers.
In [50]: pd.to_datetime(s,unit='s')
Out[50]:
0 1970-01-01 00:00:00
1 1970-01-01 00:00:01
2 1970-01-01 00:00:02
3 1970-01-01 00:00:03
4 1970-01-01 00:00:04
5 1970-01-01 00:00:05
6 1970-01-01 00:00:06
7 1970-01-01 00:00:07
8 1970-01-01 00:00:08
9 1970-01-01 00:00:09
dtype: datetime64[ns]
In [51]: pd.to_datetime(s,unit='ms')
Out[51]:
0 1970-01-01 00:00:00
1 1970-01-01 00:00:00.001000
2 1970-01-01 00:00:00.002000
3 1970-01-01 00:00:00.003000
4 1970-01-01 00:00:00.004000
5 1970-01-01 00:00:00.005000
6 1970-01-01 00:00:00.006000
7 1970-01-01 00:00:00.007000
8 1970-01-01 00:00:00.008000
9 1970-01-01 00:00:00.009000
dtype: datetime64[ns]
In [52]: pd.to_datetime(s,unit='D')
Out[52]:
0 1970-01-01
1 1970-01-02
2 1970-01-03
3 1970-01-04
4 1970-01-05
5 1970-01-06
6 1970-01-07
7 1970-01-08
8 1970-01-09
9 1970-01-10
dtype: datetime64[ns]
創(chuàng)建一個(gè)系列就很簡(jiǎn)單了
Creating a Series is then straightforward
In [54]: Series(s.values,index=pd.to_datetime(s,unit='s'))
Out[54]:
1970-01-01 00:00:00 0
1970-01-01 00:00:01 1
1970-01-01 00:00:02 2
1970-01-01 00:00:03 3
1970-01-01 00:00:04 4
1970-01-01 00:00:05 5
1970-01-01 00:00:06 6
1970-01-01 00:00:07 7
1970-01-01 00:00:08 8
1970-01-01 00:00:09 9
dtype: int64
這篇關(guān)于在 pandas.Series 中將時(shí)間戳轉(zhuǎn)換為 datetime.datetime的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!