Skip to content

Commit aa4cfde

Browse files
committed
Add parsing of UTC time in ISO format
1 parent e0418e9 commit aa4cfde

1 file changed

Lines changed: 38 additions & 3 deletions

File tree

src/bd2k/util/__init__.py

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
11
from __future__ import absolute_import
2-
from functools import wraps
3-
import pwd
2+
3+
import datetime
44
import grp
5-
import re
5+
import pwd
6+
from functools import wraps
7+
68
from threading import Lock
79

10+
import re
11+
812

913
def uid_to_name( uid ):
1014
return pwd.getpwuid( uid ).pw_name
@@ -168,6 +172,37 @@ def rfc3339_datetime_re( anchor=True ):
168172
('$' if anchor else '') )
169173

170174

175+
_rfc3339_datetime_re = rfc3339_datetime_re( )
176+
177+
178+
def parse_iso_utc( s ):
179+
"""
180+
Parses an ISO time with a hard-coded Z for zulu-time (UTC) at the end. Other timezones are
181+
not supported.
182+
183+
:param str s: the ISO-formatted time
184+
185+
:rtype: datetime.datetime
186+
187+
:return: an timezone-naive datetime object
188+
189+
>>> parse_iso_utc('2016-04-27T00:28:04.000Z')
190+
datetime.datetime(2016, 4, 27, 0, 28, 4)
191+
>>> parse_iso_utc('2016-04-27T00:28:04Z')
192+
datetime.datetime(2016, 4, 27, 0, 28, 4)
193+
>>> parse_iso_utc('2016-04-27T00:28:04X')
194+
Traceback (most recent call last):
195+
...
196+
ValueError: Not a valid ISO datetime in UTC: 2016-04-27T00:28:04X
197+
"""
198+
m = _rfc3339_datetime_re.match( s )
199+
if not m:
200+
raise ValueError( 'Not a valid ISO datetime in UTC: ' + s )
201+
else:
202+
fmt = '%Y-%m-%dT%H:%M:%S' + ('.%f' if m.group( 7 ) else '') + 'Z'
203+
return datetime.datetime.strptime( s, fmt )
204+
205+
171206
def strict_bool( s ):
172207
"""
173208
Variant of bool() that only accepts two possible string values.

0 commit comments

Comments
 (0)