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