Parse and convert ISO-8601 string to datetime.
(datestring: str)
| 51 | |
| 52 | |
| 53 | def parse_iso8601(datestring: str) -> datetime: |
| 54 | """Parse and convert ISO-8601 string to datetime.""" |
| 55 | warn("parse_iso8601", "v5.3", "v6", "datetime.datetime.fromisoformat or dateutil.parser.isoparse") |
| 56 | m = ISO8601_REGEX.match(datestring) |
| 57 | if not m: |
| 58 | raise ValueError('unable to parse date string %r' % datestring) |
| 59 | groups = m.groupdict() |
| 60 | tz = groups['timezone'] |
| 61 | if tz == 'Z': |
| 62 | tz = timezone(timedelta(0)) |
| 63 | elif tz: |
| 64 | m = TIMEZONE_REGEX.match(tz) |
| 65 | prefix, hours, minutes = m.groups() |
| 66 | hours, minutes = int(hours), int(minutes) |
| 67 | if prefix == '-': |
| 68 | hours = -hours |
| 69 | minutes = -minutes |
| 70 | tz = timezone(timedelta(minutes=minutes, hours=hours)) |
| 71 | return datetime( |
| 72 | int(groups['year']), int(groups['month']), |
| 73 | int(groups['day']), int(groups['hour'] or 0), |
| 74 | int(groups['minute'] or 0), int(groups['second'] or 0), |
| 75 | int(groups['fraction'] or 0), tz |
| 76 | ) |