0

I tried researching this question here but couldn't seem to find the correct google combination to find someone else answering the same question but if you know of a duplicate question just lmk.

I'm trying to parse a duration into a datetime. The string's will look like this: "4d2h10m30s" for 4 days 2 hours 10 minutes and 30 seconds. But I also need it to still parse if its "4d2h" for 4 days 2 hours or also "2h30m" for 2 hours and 30 minutes.

Any help is appreciated.

2 Answers2

0

There is a libray on GitHub, named pytimeparse, which seems to be doing what you want. From the documentations:

The single function pytimeparse.timeparse.timeparse defined in the library (also available as pytimeparse.parse) parses time expressions like the following:

  • 32m
  • 2h32m
  • 3d2h32m
  • 1w3d2h32m

They support many more formats, but I think this will cover your requirements.

BTW, the answer comes from How can I parse free-text time intervals in Python, ranging from years to seconds?. The Google terms I used were: python date interval parsing

Amitai Irron
  • 1,973
  • 1
  • 12
  • 14
0
def getMyTime(timeString):
    myTime = {'day': None, 'hour': None, 'minute': None, 'second': None}

    positions = []

    for item in timeString:
        if item.isalpha():
            positions.append([timeString.find(item), item])

    for i in range(len(positions)):
        value = None
        if i == 0:
            value = timeString[0:positions[i][0]]
        else:
            value = timeString[positions[i-1][0]+1:positions[i][0]]
        value = 0 if len(value.lstrip('0')) == 0 else int(value.lstrip('0'))
        if positions[i][1] == 'd':
            myTime['day'] = value
        elif positions[i][1] == 'h':
            myTime['hour'] = value
        elif positions[i][1] == 'm':
            myTime['minute'] = value
        elif positions[i][1] == 's':
            myTime['second'] = value
        else:
            pass

    return myTime

timeStrings = [
    '10d',
    '10d020h',
    '10d20h30m',
    '10d20h30m40s',
    '010d0020h00030m00040s',
    '00d00h00m00s',
    '00s00m00h00d',
    '0040s0030m0020h0010d',
    '40s30m20h10d',
    '30m20h10d',
    '20h10d',
    '10d',
]

for timeString in timeStrings:
    print(getMyTime(timeString))

Output...

{'day': 10, 'hour': None, 'minute': None, 'second': None}
{'day': 10, 'hour': 20, 'minute': None, 'second': None}
{'day': 10, 'hour': 20, 'minute': 30, 'second': None}
{'day': 10, 'hour': 20, 'minute': 30, 'second': 40}
{'day': 10, 'hour': 20, 'minute': 30, 'second': 40}
{'day': 0, 'hour': 0, 'minute': 0, 'second': 0}
{'day': 0, 'hour': 0, 'minute': 0, 'second': 0}
{'day': 10, 'hour': 20, 'minute': 30, 'second': 40}
{'day': 10, 'hour': 20, 'minute': 30, 'second': 40}
{'day': 10, 'hour': 20, 'minute': 30, 'second': None}
{'day': 10, 'hour': 20, 'minute': None, 'second': None}
{'day': 10, 'hour': None, 'minute': None, 'second': None}
anbocode
  • 53
  • 6