9

I have a series where the timestamp is in the format HHHHH:MM:

timestamp = pd.Series(['34:23', '125:26', '15234:52'], index=index)

I would like to convert it to a timedelta series.

For now I manage to do that on a single string:

str[:-3]
str[-2:]
timedelta(hours=int(str[:-3]),minutes=int(str[-2:]))

I would like to apply it to the whole series, if possible in a cleaner way. Is there a way to do this?

jpp
  • 159,742
  • 34
  • 281
  • 339
Gilles L
  • 165
  • 1
  • 3
  • 8

4 Answers4

12

You can use column-wise Pandas methods:

s = pd.Series(['34:23','125:26','15234:52'])

v = s.str.split(':', expand=True).astype(int)
s = pd.to_timedelta(v[0], unit='h') + pd.to_timedelta(v[1], unit='m')

print(s)

0     1 days 10:23:00
1     5 days 05:26:00
2   634 days 18:52:00
dtype: timedelta64[ns]

As pointed out in comments, this can also be achieved in one line, albeit less clear:

s = pd.to_timedelta((s.str.split(':', expand=True).astype(int) * (60, 1)).sum(axis=1), unit='min')
jpp
  • 159,742
  • 34
  • 281
  • 339
1

This is how I would do it:

timestamp = pd.Series(['34:23','125:26','15234:52'])
x = timestamp.str.split(":").apply(lambda x: int(x[0])*60 + int(x[1]))
timestamp = pd.to_timedelta(x, unit='s')
erncyp
  • 1,649
  • 21
  • 23
1

Parse the delta in seconds as an argument to pd.to_timedelta like this,

In [1]: import pandas as pd
In [2]: ts = pd.Series(['34:23','125:26','15234:52'])
In [3]: secs = 60 * ts.apply(lambda x: 60*int(x[:-3]) + int(x[-2:]))
In [4]: pd.to_timedelta(secs, 's')
Out[4]:
0     1 days 10:23:00
1     5 days 05:26:00
2   634 days 18:52:00
dtype: timedelta64[ns]

Edit: missed erncyp's answer which would work as well but you need to multiply the argument to pd.to_timedelta by 60 since if I recall correctly minutes aren't an available as a measure of elapsed time except modulo the previous hour.

arra
  • 136
  • 3
1

You can use pandas.Series.apply, i.e.:

def convert(args):
    return timedelta(hours=int(args[:-3]),minutes=int(args[-2:]))
s = pd.Series(['34:23','125:26','15234:52'])
s = s.apply(convert)
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268