代码之家  ›  专栏  ›  技术社区  ›  user1471980

在python中将epoch转换为可读数据时间

  •  0
  • user1471980  · 技术社区  · 7 年前

    我有一个数据框,其中一列是纪元时间:

    df1['timestamp'] 
    

    是这样的:

    1533009600000
    1533013200000  
    1533016800000 
    
    
    
    timestamp    object
    

    我需要转换成人类可读的时间戳。我试过这个:

    import time
    df1['timestamp']=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(df1['timestamp']))
    

    我得到这个错误:

    TypeError: cannot convert the series to <type 'float'>
    

    我在这里做错了什么?

    2 回复  |  直到 7 年前
        1
  •  4
  •   Vaishali    7 年前

    您可以根据纪元时间的单位进行转换。这个数字对于s来说太大了,假设它是ms

    df['timestamp'] = pd.to_datetime(df['timestamp'], unit = 'ms')
    
    
        timestamp
    0   2018-07-31 04:00:00
    1   2018-07-31 05:00:00
    2   2018-07-31 06:00:00
    
        2
  •  0
  •   Dani Mesejo    7 年前

    df1['timestamp'] 到函数 time.localtime . 将您的行改为:

    df1['timestamp'] = df1['timestamp'].apply(lambda timestamp: time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp)))
    

    这将对序列中的每个值应用函数。