2

I have an amount of seconds in a dataframe, let's say:

s = 122

I want to convert it to the following format:

00:02:02.0000

To do that I try using to_datetime the following way:

 pd.to_datetime(s, format='%H:%M:%S.%f')

However this doesn't work:

ValueError: time data 122 does not match format '%H:%M:%S.%f' (match)

I also tried using unit='ms' instead of format, but then I get the date before the time. How can I modify my code to get the desired convertion ?

It needs to be done in the dataframe using pandas if possible.

EDIT: both jezrael and MedAli solutions below are valid, however Jezrael solution have the advantage to work not only with integers but also with Datetime.time as input!

Vincent Teyssier
  • 2,146
  • 5
  • 25
  • 62
  • I sugegst use `timedelta` - `datetime.timedelta(seconds=s)` – jezrael Jul 09 '18 at 14:09
  • This is not a duplicate since I am trying to achieve that using Pandas functions, not string to date from the standard library. Thanks, but will that work on the whole dataframe ? – Vincent Teyssier Jul 09 '18 at 14:11

2 Answers2

2

Use to_timedelta with convert seconds to nanoseconds:

df = pd.DataFrame({'sec':[122,3,5,7,1,0]})

df['t'] = pd.to_timedelta(df['sec'] * 10**9)

print (df)
   sec        t
0  122 00:02:02
1    3 00:00:03
2    5 00:00:05
3    7 00:00:07
4    1 00:00:01
5    0 00:00:00
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
1

You can edit your code as follows to get the desired result:

df = pd.DataFrame({'sec':[122,3,5,7,1,0]})
df['time'] = pd.to_datetime(df.sec, unit="s").dt.time

Output:

In [10]: df
Out[10]: 
   sec      time
0  110  00:01:50
1    3  00:00:03
2    5  00:00:05
3    7  00:00:07
4    1  00:00:01
5    0  00:00:00
Mohamed Ali JAMAOUI
  • 14,275
  • 14
  • 73
  • 117