Skip to content
This repository has been archived by the owner on Jul 24, 2024. It is now read-only.

Commit

Permalink
Update hms_to_seconds
Browse files Browse the repository at this point in the history
  • Loading branch information
kt474 committed Sep 19, 2023
1 parent fdefd3c commit cb04367
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 14 deletions.
33 changes: 23 additions & 10 deletions qiskit_ibm_provider/utils/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

"""Utilities related to conversion."""

import re
from datetime import datetime, timedelta, timezone
from math import ceil
from typing import Union, Tuple, Any, Optional
Expand Down Expand Up @@ -200,13 +201,25 @@ def hms_to_seconds(hms: str, msg_prefix: str = "") -> int:
Raises:
IBMInputValueError: when the given hms string is in an invalid format
"""
try:
date_time = parser.parse(hms)
hours = date_time.hour
minutes = date_time.minute
seconds = date_time.second
return int(
timedelta(hours=hours, minutes=minutes, seconds=seconds).total_seconds()
)
except parser.ParserError as parser_error:
raise IBMInputValueError(msg_prefix + str(parser_error))

parsed_time = re.findall(r"(\d+[dhms])", hms)
total_seconds = 0

if parsed_time:
for time_unit in parsed_time:
unit = time_unit[-1]
value = int(time_unit[:-1])
if unit == "d":
total_seconds += value * 86400
elif unit == "h":
total_seconds += value * 3600
elif unit == "m":
total_seconds += value * 60
elif unit == "s":
total_seconds += value
else:
raise IBMInputValueError(f"{msg_prefix} Invalid input: {unit}")
else:
raise IBMInputValueError(f"{msg_prefix} Invalid input: {parsed_time}")

return total_seconds
7 changes: 3 additions & 4 deletions test/unit/test_utils_converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,11 @@ def test_hms_to_seconds(self):
("3h 30m 30s", 12630),
("3h 30s", 10830),
("3h30m30s", 12630),
("2d", 172800),
("25h", 90000),
("1d 1h 1m 1s", 90061),
]
invalid_strings = [
"2d",
"24h",
"60m",
"60s",
"2w",
]
for valid_string in valid_strings:
Expand Down

0 comments on commit cb04367

Please sign in to comment.