2

I'm trying to get RFC3339 compatible output from python's time module, using the time.strftime() function.

With the Linux 'date' command, I can use a format string like the following: "date +%F_%T%:z"

$ date +%F_%T%:z
2017-06-29_16:13:29-07:00

When used with python time.strftime, the %:z appears to not be supported.

$ python
>>> import time
>>> print time.strftime("%F %T%:z")
2017-06-29 16:16:15%:z

Apparently, '%z' is supported, but '%:z' is not:

>>> print time.strftime("%F %T%z")
2017-05-29 16:15:35-0700

RFC3339 specifically uses the timezone offset with the embedded colon. That would be 07:00 in my case, instead of 0700.

I believe the omission of support for the "%:z' option is due to the underlying C implementation of strftime() not supporting the versions of timezone offset formatters with colons. That is '%:z', '%::z', etc.

Is there any workaround for this (e.g. another python module, or some option I'm missing int the 'time' module), other than writing code to get %z output and reformat it in %:z format, to solve this problem?

EDIT: Another question (Generate RFC 3339 timestamp in Python) gives solutions for other modules that can be used to output RFC3339 output. I'm going to self-answer with information that I found for the question in the title.

Tim Bird
  • 1,104
  • 9
  • 16
  • Possible duplicate of [Generate RFC 3339 timestamp in Python](https://stackoverflow.com/questions/8556398/generate-rfc-3339-timestamp-in-python) – viraptor Jun 29 '17 at 23:43
  • There is a [RFC3339](https://pypi.python.org/pypi/rfc3339) module on PyPI that might do what you want. – import random Jun 30 '17 at 04:12

1 Answers1

2

The strict answer to the question in the title "Does python time.strftime process timezone options correctly (for RFC3339)?" is: No.

The "%:z" supported by the Linux 'date' command is a GNU extension, and is not in the POSIX spec, or in the C implementation of strftime (as of this writing).

With regards to workarounds (requested in the body of the question), answers in Generate RFC 3339 timestamp in Python can be used as alternatives time.strftime to output RFC3339-compliant software.

Specifically, I used the pytz module to get timezone information, and datetime class isoformat() function to print in RFC3339-compliant format (with a colon in the timezone offset portion of the output). Like so: (in Python 2.7 on Ubuntu 14.04)

>>> import pytz, datetime
>>> latz = pytz.timezone("America/Los_Angeles")
>>> latz
<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>
>>> dt = datetime.datetime.now(latz)
>>> dt2 = datetime.datetime(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0, latz)
>>> dt2.isoformat()
'2017-07-06T11:50:07-08:00'

Note the conversion from dt to dt2, to set microseconds to 0. This prevents isoformat from printing microseconds as a decimal portion of seconds in the isoformat output (which RFC3339 does not support)

Tim Bird
  • 1,104
  • 9
  • 16