【问题标题】:Pandas convert integer into date熊猫将整数转换为日期
【发布时间】:2017-03-05 21:18:29
【问题描述】:

所以我有一个名为“df”的 DataFrame 对象,我试图将“时间戳”转换为实际可读的日期。

     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   

这显然是错误的,因为我知道日期应该是今年或去年。

我做错了什么?

【问题讨论】:

    标签: date pandas


    【解决方案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]
    

    【讨论】:

      【解决方案2】:

      单元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']) --> 给出 --> pandas.core.series.Series
      • 可能有一些不良数据 - 使用 (pd.to_datetime(df.timestamp, unit='ms', errors='coerce')) 将它们转换为 NaN。您也可以通过print df[pd.to_datetime(df.timestamp, unit='ms', errors='coerce').isnull()] 检查此行
      • 如果我做 df.timestamp = df.timestamp.to_datetime() 我得到错误 AttributeError: 'Series' object has no attribute 'to_datetime'
      • df[pd.to_datetime(df.timestamp, unit='ms', errors='coerce').isnull()] 返回一个空数据框
      • print (pd.to_datetime(df.timestamp, unit='ms', errors='coerce')) 也给出了错误的答案,就像以前一样
      猜你喜欢
      • 2015-09-19
      • 2018-08-09
      • 2021-09-16
      • 2021-11-09
      • 1970-01-01
      • 2018-12-08
      • 1970-01-01
      相关资源
      最近更新 更多