Suppose you have a string like the following:
str_one = '03H 49m 06s'
str_two = '18m 23s'
str_three = '56s'
How could such strings be converted to integer seconds such that the output is as follows (correspondingly)?
13746
1103
56
Suppose you have a string like the following:
str_one = '03H 49m 06s'
str_two = '18m 23s'
str_three = '56s'
How could such strings be converted to integer seconds such that the output is as follows (correspondingly)?
13746
1103
56
Solution
Produces
Explanation
We will use the datetime module, which is geared towards working with dates and times. The plan is to start by having a tuple with all possible date formats. The meaning of the %something is in this table: https://docs.python.org/en/3/library/datetime.html#strftime-and-strptime-format-codes .
We then iterate through that tuple testing one by one if the string is in the expected format. If an error of type ValueError occurs, it means that the attempt to convert it to that format failed, we silently failed and moved on to the next one. If we looped through the entire tuple and no format worked, we produce an error.
If there was success with any format, we stop the loop and go on to get the number of seconds. datetime.strptime returns a datetime object, that is, a date and time. We will use the part of the hour (hour attribute), minute (minute attribute) and second (second attribute) and do the respective conversions, to finally return the resulting number.
Why is using this better than processing the string "manually" or with regex?
final clarification
The posted code only takes into account the possible formats mentioned in the question. That means it accepts strings like "A zero-padded hour, minute, and second followed by an H, m, s respectively (note the uppercase H)". If you want to take into account more formats, you will have to add them to the tuple.
After some thought, the only thing I could think of was to create a custom function called
from_str_to_seconds
that takes as input a string of the forms:00H 00m 00s
00m 00s
00s
From these strings, the function takes the specific chunks that contain the numbers, then converts those numbers to integers which are then multiplied by their equivalent converter, and finally adds them all together to return the net number of seconds:
Tests