[英]Convert Pandas time series: UNIX epoch to datetime
我打算將以下系列的 UNIX 紀元轉換為常規日期時間對象:
>> val = pd.Series(["1440643875", "1440644191", "1440645638", "1440998720"])
>> val
0 1440643875
1 1440644191
2 1440645638
3 1440998720
Name: obj, dtype: object
似乎有兩種方法可以做到這一點。 第一個是:
>> pd.to_datetime(val, unit='s')
ValueError: year is out of range
第二個:
val.astype("datetime64[s]")
TypeError: Cannot parse "1445124547" as unit 's' using casting rule 'same_kind'
這里似乎有什么問題?
我還嘗試使用“在線紀元計算器”工具檢查這些時間戳,他們給出了合理的答案。
問題是元素是字符串,而不是整數。 顯然, pd.to_datetime()
不夠智能,無法將字符串轉換為日期時間。
我的解決方案是這樣的:
>> val.astype('int').astype("datetime64[s]")
0 2015-08-27 02:51:15
1 2015-08-27 02:56:31
2 2015-08-27 03:20:38
3 2015-08-31 05:25:20
dtype: datetime64[ns]
已編輯
datetime.datetime.utcfromtimestamp
只能得到整數作為參數:
In [510]: datetime.datetime.utcfromtimestamp('1440643875')
TypeError: an integer is required (got type str)
所以首先你需要將你的系列轉換為 int 然后你可以使用這些方法:
import pandas as pd
import datetime
s = pd.Series(["1440643875", "1440644191", "1440645638", "1440998720"], dtype=object)
s = pd.to_numeric(s)
In [50]: s
Out[50]:
0 1440643875
1 1440644191
2 1440645638
3 1440998720
dtype: int64
In [51]: pd.to_datetime(s, unit='s')
Out[51]:
0 2015-08-27 02:51:15
1 2015-08-27 02:56:31
2 2015-08-27 03:20:38
3 2015-08-31 05:25:20
dtype: datetime64[ns]
還有 @Adam Smith 在評論中指出的datetime.datetime.utcfromtimestamp
:
In [52]: s.apply(datetime.datetime.utcfromtimestamp)
Out[52]:
0 2015-08-27 02:51:15
1 2015-08-27 02:56:31
2 2015-08-27 03:20:38
3 2015-08-31 05:25:20
dtype: datetime64[ns]
我們可以直接將紀元時間轉換為日期時間。 默認情況下,它將使用 pd.to_datetime 以 %Y-%m-%d %I:%M:%S 格式。 通過使用 dt.strftime 可以將完整的列格式化為所需的格式。
from datetime import datetime as dt
import pandas as pd
input_data_df['timestamp']=pd.to_datetime(input_data_df['epoch'],unit='ms')
input_data_df['timestamp'] = input_data_df['timestamp'].dt.strftime('%d-%m-%Y %I:%M:%S')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.