1

Have a dataframe: need to convert a timestamp column to datetime

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

This is ok for one value but I need to have this result for a dataframe column named 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)

I expect all the values of the columm time_q to be for example 28-02-2019 10:11:12 and others values with this format; instead i have an error message

1 Answers1

3

try this

# 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"] = data_pre["time_q"].apply(lambda x: datetime.utcfromtimestamp(x).strftime('%d-%m-%Y %H:%M:%S'))
patrick-fitzgerald
  • 2,561
  • 3
  • 35
  • 49
tawab_shakeel
  • 3,701
  • 10
  • 26