繁体   English   中英

将 Pandas 时间序列:UNIX 纪元转换为日期时间

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM