Last active
November 29, 2020 11:13
-
-
Save Ayehavgunne/ac6108fa8740c325892b to your computer and use it in GitHub Desktop.
Parse a string into a timedelta object in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from decimal import Decimal | |
from datetime import timedelta | |
def duration(duration_string): #example: '5d3h2m1s' | |
duration_string = duration_string.lower() | |
total_seconds = Decimal('0') | |
prev_num = [] | |
for character in duration_string: | |
if character.isalpha(): | |
if prev_num: | |
num = Decimal(''.join(prev_num)) | |
if character == 'd': | |
total_seconds += num * 60 * 60 * 24 | |
elif character == 'h': | |
total_seconds += num * 60 * 60 | |
elif character == 'm': | |
total_seconds += num * 60 | |
elif character == 's': | |
total_seconds += num | |
prev_num = [] | |
elif character.isnumeric() or character == '.': | |
prev_num.append(character) | |
return timedelta(seconds=float(total_seconds)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment