Pandas将整数转换为日期

3

我有一个名为“df”的DataFrame对象,我正在尝试将“timestamp”转换成实际可读的日期。

     timestamp
0   1465893683657       
1   1457783741932   
2   1459730006393   
3   1459744745346   
4   1459744756375   

我尝试过

df['timestamp'] = pd.to_datetime(df['timestamp'],unit='s')

但这会导致
     timestamp
0   1970-01-01 00:24:25.893683657   
1   1970-01-01 00:24:17.783741932   
2   1970-01-01 00:24:19.730006393   
3   1970-01-01 00:24:19.744745346   
4   1970-01-01 00:24:19.744756375   

"这显然是错误的,因为我知道日期应该是今年或去年。我做错了什么?"
2个回答

4
使用单位为毫秒(ms)的解决方案:
print (pd.to_datetime(df.timestamp, unit='ms'))
0   2016-06-14 08:41:23.657
1   2016-03-12 11:55:41.932
2   2016-04-04 00:33:26.393
3   2016-04-04 04:39:05.346
4   2016-04-04 04:39:16.375
Name: timestamp, dtype: datetime64[ns]

没有一个答案适用于我。我得到了与之前相同的结果。更多信息:type(df['timestamp']) --> gives --> pandas.core.series.Series - Runner Bean
也许存在一些坏数据 - 使用 (pd.to_datetime(df.timestamp, unit='ms', errors='coerce')) 将它们转换为 NaN。您还可以通过 print df[pd.to_datetime(df.timestamp, unit='ms', errors='coerce').isnull()] 检查这些行。 - jezrael
如果我执行 df.timestamp = df.timestamp.to_datetime(),会出现 AttributeError: 'Series' object has no attribute 'to_datetime' 错误。 - Runner Bean
df[pd.to_datetime(df.timestamp, unit='ms', errors='coerce').isnull()] 返回一个空的数据框。 - Runner Bean
print(pd.to_datetime(df.timestamp, unit='ms', errors='coerce'))同样会给出错误的答案,就像之前一样。 - Runner Bean
抱歉;-)我的错,我做错了什么,你的答案完美地解决了问题! - Runner Bean

1
您可以减少有效数字,或更好地使用@jezrael的单位(“ms”)。
In [133]: pd.to_datetime(df.timestamp // 10**3, unit='s')
Out[133]:
0   2016-06-14 08:41:23
1   2016-03-12 11:55:41
2   2016-04-04 00:33:26
3   2016-04-04 04:39:05
4   2016-04-04 04:39:16
Name: timestamp, dtype: datetime64[ns]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接