2

Epoch value of time is converted as follows for a particular epoch value:

time.strftime("%H:%M:%S ", time.localtime(28000000000))  
Out[82]: '07:16:40 '     

But when I apply the above method to a column of epoch time in the dataset,

time.strftime("%H:%M:%S ", time.localtime(df1['d']))

I am getting following error:

TypeError: cannot convert the series to type 'float'

Where I am going wrong?

df1['d'] is epoch time duration which have data as follows in the column:

28000000000
16000000000
33000000000
28000000000
27000000000
22000000000
26000000000
22000000000
22000000000
22000000000
46000000000

I need the epoch time not the datetime object format.

surya rahul
  • 833
  • 2
  • 14
  • 27
  • what is the value of time.localtime(df1['d']) ? – sachin dubey Jul 18 '18 at 09:10
  • Hello @sachindubey value of `time.localtime(df1['d'])` gives `TypeError: cannot convert the series to ` – surya rahul Jul 18 '18 at 09:13
  • sorry i mean value of df1['d'] ? – sachin dubey Jul 18 '18 at 09:14
  • df1['d'] have epoch time durations in a column like 28000000000 16000000000 33000000000 28000000000 27000000000 22000000000 26000000000 22000000000 22000000000 22000000000 46000000000 I will add these value in main section. – surya rahul Jul 18 '18 at 09:17
  • Possible duplicate of [Convert unix time to readable date in pandas DataFrame](https://stackoverflow.com/questions/19231871/convert-unix-time-to-readable-date-in-pandas-dataframe) – Georgy Jul 18 '18 at 09:24
  • my question is regarding time duration in epoch whereas the link you have shared is regarding `datetime` objects @Georgy – surya rahul Jul 18 '18 at 09:47

2 Answers2

3

I think need Series.apply with lambda function:

df1 = pd.DataFrame({'d':[28000000000,28000000000]})

df1['times'] = df1['d'].apply(lambda x: time.strftime("%H:%M:%S", time.localtime(x)))

Or list comprehension:

df1['times'] = [time.strftime("%H:%M:%S", time.localtime(x)) for x in df1['d']]

print (df1)
             d     times
0  28000000000  03:46:40
1  28000000000  03:46:40
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Yes, both of the above methods works. Thanks. One doubt what if multiple columns are needed to transform this way , is it possible ? – surya rahul Jul 18 '18 at 09:32
  • Yes, it is possible,`cols = ['d','d1','d2']` and then `df1[cols] = df1[cols].applymap(lambda x: time.strftime("%H:%M:%S", time.localtime(x)))` – jezrael Jul 18 '18 at 09:34
1

You can use map function.

import pandas as pd
import time

df = pd.DataFrame([[28000000000, 2.5], [28100000000, 2.54]], columns=['d', 'e'])

df['time'] = df.d.map(lambda t: time.strftime("%H:%M:%S ", time.localtime(t)))
print(df)
#              d     e       time
# 0  28000000000  2.50  03:46:40 
# 1  28100000000  2.54  13:33:20 
Gelineau
  • 2,031
  • 4
  • 20
  • 30