| 1 |
# Copyright (c) Microsoft Corporation. |
| 2 |
# Licensed under the MIT License. |
| 3 |
|
| 4 |
import re |
| 5 |
from datetime import timedelta |
| 6 |
|
| 7 |
from dateutil import parser |
| 8 |
|
| 9 |
# Regex for TimeSpan |
| 10 |
_TIMESPAN_PATTERN = re.compile(r"(-?)((?P<d>[0-9]*).)?(?P<h>[0-9]{2}):(?P<m>[0-9]{2}):(?P<s>[0-9]{2}(\.[0-9]+)?$)") |
| 11 |
|
| 12 |
|
| 13 |
def to_datetime(value): |
| 14 |
"""Converts a string to a datetime.""" |
| 15 |
if isinstance(value, int): |
| 16 |
return parser.parse(value) |
| 17 |
return parser.isoparse(value) |
| 18 |
|
| 19 |
|
| 20 |
def to_timedelta(value): |
| 21 |
"""Converts a string to a timedelta.""" |
| 22 |
if isinstance(value, (int, float)): |
| 23 |
return timedelta(microseconds=(float(value) / 10)) |
| 24 |
match = _TIMESPAN_PATTERN.match(value) |
| 25 |
if match: |
| 26 |
if match.group(1) == "-": |
| 27 |
factor = -1 |
| 28 |
else: |
| 29 |
factor = 1 |
| 30 |
return factor * timedelta(days=int(match.group("d") or 0), hours=int(match.group("h")), minutes=int(match.group("m")), seconds=float(match.group("s"))) |
| 31 |
else: |
| 32 |
raise ValueError("Timespan value '{}' cannot be decoded".format(value)) |