Skip to content

Commit

Permalink
Merge pull request #217 from boxine/fromisoformat
Browse files Browse the repository at this point in the history
Enhance parse_dt()
  • Loading branch information
phihag authored Oct 29, 2024
2 parents a833c44 + 5a3d3d4 commit 43f6374
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ Doc-Write, see: https://github.com/boxine/bx_py_utils/blob/master/bx_py_utils/do

#### bx_py_utils.test_utils.datetime

* [`parse_dt()`](https://github.com/boxine/bx_py_utils/blob/master/bx_py_utils/test_utils/datetime.py#L4-L15) - Helper for easy generate a `datetime` instance via string.
* [`parse_dt()`](https://github.com/boxine/bx_py_utils/blob/master/bx_py_utils/test_utils/datetime.py#L5-L25) - Helper for easy generate a `datetime` instance via string.

#### bx_py_utils.test_utils.deny_requests

Expand Down
2 changes: 1 addition & 1 deletion bx_py_utils/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = '104'
__version__ = '105'
12 changes: 11 additions & 1 deletion bx_py_utils/test_utils/datetime.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import datetime
import sys


def parse_dt(dtstr):
Expand All @@ -9,7 +10,16 @@ def parse_dt(dtstr):
True
>>> parse_dt('2020-01-01T00:00:00+0000')
datetime.datetime(2020, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)
>>> parse_dt('2020-01-02T03:04:05.678901+00:00')
datetime.datetime(2020, 1, 2, 3, 4, 5, 678901, tzinfo=datetime.timezone.utc)
"""
if dtstr is None:
return None
return datetime.datetime.strptime(dtstr, '%Y-%m-%dT%H:%M:%S%z')

try:
return datetime.datetime.fromisoformat(dtstr)
except ValueError:
if sys.version_info[:2] == (3, 10):
# Python 3.10 supports only formats emitted by date.isoformat() or datetime.isoformat() :(
return datetime.datetime.strptime(dtstr, '%Y-%m-%dT%H:%M:%S%z')
raise

0 comments on commit 43f6374

Please sign in to comment.