0

I took from a previous post a way to capture seconds into HH:MM:SS format to render a properly formatted column into a table visual

str(datetime.timedelta(seconds=12345))

Output looks like this: 22:00:01

And I need this back to int (seconds)

I need to reverse engineer this back to int

How can I do this

Roger Steinberg
  • 1,554
  • 2
  • 18
  • 46
  • You can simply use `datetime.timedelta(seconds=12345).total_seconds()` provided you don't convert the datetime.timedelta object to a string. – Ghoti Oct 06 '21 at 17:03
  • If you must convert the datetime.timedelta object to string, you'll have to convert back with `strptime` (reference: https://stackoverflow.com/questions/8365380/how-to-convert-string-to-datetime-timedelta) – Ghoti Oct 06 '21 at 17:04
  • @Ghoti `strptime` is a bad choice for converting timedelta string to timedelta object, fist it gives you a datetime object, and second, it is restricted to 24h clock, e.g. will not parse `"25:00:00"` (duration of 25 hours). – FObersteiner Oct 07 '21 at 07:44
  • `pandas` has [a parser for this](https://pandas.pydata.org/docs/reference/api/pandas.to_timedelta.html)... other than that, this totally depends on your format. Could you please share an example? – FObersteiner Oct 07 '21 at 07:45
  • @MrFuppes done added an example – Roger Steinberg Oct 07 '21 at 12:41
  • ok so basically you want to parse the output of e.g. `str(datetime.timedelta(seconds=12345))` back to a timedelta object? – FObersteiner Oct 07 '21 at 13:30
  • no back to integer values so I should get 12345 – Roger Steinberg Oct 07 '21 at 13:31

1 Answers1

1

basically, you'd split the string on space to get the "days" part, split again on colon to get the H/M/S part. From there on it's just some simple math. Ex:

def tdstring_to_integerseconds(tdstr: str) -> int:
    parts = tdstr.strip(' ').split(' ') # clean surrounding spaces and split
    d = 0 # day default to zero...
    if len(parts) > 1: # if more than one part, we have days specified
        d = int(parts[0])
    s = sum(x*y for x, y in zip(map(int, parts[-1].split(':')), (3600, 60, 1)))
    return 86400*d + s

giving you for example

from datetime import timedelta

for td in timedelta(1), timedelta(-1), timedelta(0.5), timedelta(-1.5):
    print(str(td), '->', tdstring_to_integerseconds(str(td)))

# 1 day, 0:00:00 -> 86400
# -1 day, 0:00:00 -> -86400
# 12:00:00 -> 43200
# -2 days, 12:00:00 -> -129600
FObersteiner
  • 22,500
  • 8
  • 42
  • 72