pyrfc3339.parser – Parse RFC 3339 timestamps

pyrfc3339.parser.parse(timestamp: str, utc: bool = False, produce_naive: bool = False) datetime

Parse an RFC 3339-formatted timestamp and return a datetime.datetime.

If the timestamp is presented in UTC, then the tzinfo attribute of the returned datetime will be set to datetime.timezone.utc.

>>> parse('2009-01-01T10:01:02Z')
datetime.datetime(2009, 1, 1, 10, 1, 2, tzinfo=datetime.timezone.utc)

Otherwise, a datetime.timezone instance is created with the appropriate offset, and the tzinfo attribute of the returned datetime is set to that value.

>>> parse('2009-01-01T14:01:02-04:00')
datetime.datetime(2009, 1, 1, 14, 1, 2, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))

However, if parse() is called with utc=True, then the returned datetime will be normalized to UTC (and its tzinfo attribute set to utc), regardless of the input timezone.

>>> parse('2009-01-01T06:01:02-04:00', utc=True)
datetime.datetime(2009, 1, 1, 10, 1, 2, tzinfo=datetime.timezone.utc)

As parsing is delegated to datetime.datetime.fromisoformat(), certain timestamps which do not strictly adhere to RFC 3339 are nonetheless accepted.

>>> parse('2009-01-01T06:01:02')
datetime.datetime(2009, 1, 1, 6, 1, 2)

Exceptions will, however, be thrown for blatantly invalid input:

>>> parse('2009-01-01T25:01:02Z')
Traceback (most recent call last):
...
ValueError: hour must be in 0..23
Parameters:
  • timestamp (str) – the RFC 3339 timestamp to be parsed

  • utc (bool) – True to normalize the timestamp to UTC; False otherwise. Defaults to False.

  • produce_naive (bool) – True if the produced datetime instance should not have a timezone attached (that is, be ‘naive’); False otherwise. Defaults to False.

Returns:

the parsed timestamp

Return type:

datetime.datetime