Serialize a datetime including timezone info. Uses the timezone info provided if present, otherwise uses the current runtime's timezone info. UTC datetimes end in "Z" while all other timezones are represented as offset from UTC, e.g. +05:00.
(v: dt.datetime)
| 4 | |
| 5 | |
| 6 | def serialize_datetime(v: dt.datetime) -> str: |
| 7 | """ |
| 8 | Serialize a datetime including timezone info. |
| 9 | |
| 10 | Uses the timezone info provided if present, otherwise uses the current runtime's timezone info. |
| 11 | |
| 12 | UTC datetimes end in "Z" while all other timezones are represented as offset from UTC, e.g. +05:00. |
| 13 | """ |
| 14 | |
| 15 | def _serialize_zoned_datetime(v: dt.datetime) -> str: |
| 16 | if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): |
| 17 | # UTC is a special case where we use "Z" at the end instead of "+00:00" |
| 18 | return v.isoformat().replace("+00:00", "Z") |
| 19 | else: |
| 20 | # Delegate to the typical +/- offset format |
| 21 | return v.isoformat() |
| 22 | |
| 23 | if v.tzinfo is not None: |
| 24 | return _serialize_zoned_datetime(v) |
| 25 | else: |
| 26 | local_tz = dt.datetime.now().astimezone().tzinfo |
| 27 | localized_dt = v.replace(tzinfo=local_tz) |
| 28 | return _serialize_zoned_datetime(localized_dt) |
no test coverage detected
searching dependent graphs…