熊猫如何将时间戳列转换为日期时间?

时间:2019-07-21 15:30:32

标签: pandas datetime timestamp

具有数据框:需要将时间戳列转换为日期时间

 readable = datetime.utcfromtimestamp(1551348672).strftime('%d-%m-%Y 
 %H:%M:%S')
 print(readable) 28-02-2019 10:11:12

这对于一个值是可以的,但对于名为time_q的数据框列,我需要具有该结果

data_pre["time_q"] = data_pre["time_q"].map(lambda x: 
datetime.utcfromtimestamp(str(x)).strftime('%d-%m-%Y %H:%M:%S'))

Traceback (most recent call last)
     <ipython-input-65-7f8191ae6c70> in <module>
----> 1 data_pre["time_q"] = data_pre["time_q"].map(lambda x: 
     datetime.utcfromtimestamp(str(x)).strftime('%d-%m-%Y %H:%M:%S'))

~\Anaconda3\lib\site-packages\pandas\core\series.py in map(self, arg, 
na_action)
   2996         """
   2997         new_values = super(Series, self)._map_values(
-> 2998             arg, na_action=na_action)
  2999         return self._constructor(new_values,
  3000                                  
index=self.index).__finalize__(self)

~\Anaconda3\lib\site-packages\pandas\core\base.py in _map_values(self, 
mapper, na_action)
   1002 
   1003         # mapper is a function
-> 1004         new_values = map_f(values, mapper)
   1005 
      1006         return new_values

pandas/_libs/src\inference.pyx in pandas._libs.lib.map_infer()

<ipython-input-65-7f8191ae6c70> in <lambda>(x)
----> 1 data_pre["time_q"] = data_pre["time_q"].map(lambda x: 
datetime.utcfromtimestamp(str(x)).strftime('%d-%m-%Y %H:%M:%S'))

TypeError: an integer is required (got type str)

我希望列time_q的所有值都是例如28-02-2019 10:11:12以及其他具有这种格式的值;相反,我有一条错误消息

1 个答案:

答案 0 :(得分:0)

尝试

# if the time_q is not int then convert first to int
data_pre['time_q'] = data_pre['time_q'].astype(int)
data_pre["time_q"].apply(lambda x: datetime.utcfromtimestamp(x).strftime('%d-%m-%Y %H:%M:%S'))