1"""
2This module defines a method to parse an ISO 8601:2004 date time string.
3
4For this job it uses the parse_date and parse_time methods defined in date
5and time module.
6"""
7
8from datetime import datetime
9
10from isodate.isodates import parse_date
11from isodate.isoerror import ISO8601Error
12from isodate.isostrf import DATE_EXT_COMPLETE, TIME_EXT_COMPLETE, TZ_EXT, strftime
13from isodate.isotime import parse_time
14
15
16def parse_datetime(datetimestring):
17 """
18 Parses ISO 8601 date-times into datetime.datetime objects.
19
20 This function uses parse_date and parse_time to do the job, so it allows
21 more combinations of date and time representations, than the actual
22 ISO 8601:2004 standard allows.
23 """
24 try:
25 datestring, timestring = datetimestring.split("T")
26 except ValueError:
27 raise ISO8601Error(
28 "ISO 8601 time designator 'T' missing. Unable to"
29 " parse datetime string %r" % datetimestring
30 )
31 tmpdate = parse_date(datestring)
32 tmptime = parse_time(timestring)
33 return datetime.combine(tmpdate, tmptime)
34
35
36def datetime_isoformat(
37 tdt, format=DATE_EXT_COMPLETE + "T" + TIME_EXT_COMPLETE + TZ_EXT
38):
39 """
40 Format datetime strings.
41
42 This method is just a wrapper around isodate.isostrf.strftime and uses
43 Extended-Complete as default format.
44 """
45 return strftime(tdt, format)