python: parsing the output of datetime.isoformat()

I couldn’t find this explicitly anywhere, so here it is. A function to parse a string which was generated by datetime.isoformat()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import datetime

def parse_iso_datetime(str) :
# parse a datetime generated by datetime.isoformat()
try :
return datetime.datetime.strptime(str, "%Y-%m-%dT%H:%M:%S")
except ValueError :
return datetime.datetime.strptime(str, "%Y-%m-%dT%H:%M:%S.%f")

# and a simple test case
def test() :
d = datetime.datetime.now()
assert parse_iso_datetime(d.isoformat()) == d
d = datetime.datetime.now().replace(microsecond = 0)
assert parse_iso_datetime(d.isoformat()) == d