You want to use Timedelta
objects. datetime
has one too, but I prefer pandas
import pandas as pd
td = pd.Timedelta('200hr 28min 49sec')
You can add, subtract and divide timedeltas. To do more calculations you might want to work with td.total_seconds()
.
But printing the timedelta gives you a different format:
>>> td
Timedelta('8 days 08:28:49')
Solution: Write your own format function
def timedelta_to_str(td):
h = td // pd.Timedelta('1h')
td -= pd.Timedelta(hours = h)
m = td // pd.Timedelta('1m')
td -= pd.Timedelta(minutes = m)
s = td.seconds
return f'{h}hr {m}min {s}sec'
>>> timedelta_to_str(td)
200hr 28min 49sec
To use this format within a DataFrame you might want to use this hack:
pd.Timedelta.__repr__ = timedelta_to_str
This changes the default representation of all Timedelta Objects!
Or you might want to use inheritance to make it super clean:
class myTimedelta(pd.Timedelta):
def __repr__(self):
td = pd.Timedelta(self) # make a copy
h = td // pd.Timedelta('1h')
td -= pd.Timedelta(hours = h)
m = td // pd.Timedelta('1m')
td -= pd.Timedelta(minutes = m)
s = td.seconds
return f'{h}hr {m}min {s}sec'
>>> myTimedelta('200hr 28min 49sec')
200hr 28min 49sec
>>> myTimedelta('200hr 28min 49sec') + myTimedelta('1hr')
201hr 28min 49sec