ninjecto.utils.iso8601¶Utilities to handle ISO 8601 formatted dates.
iso8601_to_datetime():
Converts a date in the ISO8601 with timezone format to a datetime objectdatetime_to_iso8601():
Converts a datetime object to a date string of the ISO8601 with timezone.ninjecto.utils.iso8601.iso8601_to_datetime(whenstr)¶Converts a date in the ISO8601 with timezone format to a datetime object with timezone.
The format is of the form `` YYYY-MM-DDTHH:MM:SS.MS-TZ``, for example:
2020-06-10T01:47:35.186550-06:00
Prior to Python 3.7, datetime.datetime.strptime() ``%z`` was
only able to parse the timezone when using the ±HHMM[SS[.ffffff]]
format.
To workaround this limitation, we literally strip the last (first rightmost) colon using:
''.join(now.rsplit(':', 1))
And that’s enough to make datetime.datetime.strptime() to parse
ISO8601 with timezone dates correctly and is compatible with any Python
version 3.5 or higher.
datetime.datetimeninjecto.utils.iso8601.datetime_to_iso8601(whendt)¶Converts a datetime object to a date string of the ISO8601 with timezone.
The format is of the form YYYY-MM-DDTHH:MM:SS.MS-TZ, for example:
2020-06-10T01:47:35.186550-06:00
Datetime object. Any naive datetime object is considered a local timezone datetime. To correctly pass a UTC datetime use:
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
DateTimeJSONEncoder:
Custom JSON enconder that converts any datetime object to a ISO 8601ninjecto.utils.iso8601.DateTimeJSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)¶Custom JSON enconder that converts any datetime object to a ISO 8601 date string.
Inheritance
default(o)¶Implement this method in a subclass such that it returns
a serializable object for o, or calls the base implementation
(to raise a TypeError).
For example, to support arbitrary iterators, you could implement default like this:
def default(self, o):
try:
iterable = iter(o)
except TypeError:
pass
else:
return list(iterable)
# Let the base class default method raise the TypeError
return JSONEncoder.default(self, o)