Search code examples
pythontimetimedelta

How to convert a string formatted timedelta back to int column in seconds


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


Solution

  • 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