Python与RFC 3339时间戳
我在哪里可以找到一个用来生成RFC 3339时间格式的程序?
3 个回答
0
rfc3339 是一种非常灵活的时间格式标准,详细内容可以查看这个链接:http://www.ietf.org/rfc/rfc3339.txt。它实际上定义了很多种格式。你几乎可以通过标准的 Python 时间格式化方法来生成所有这些格式,具体可以参考这个链接:http://docs.python.org/3.3/library/datetime.html#strftime-strptime-behavior。
不过,有一个特别的地方,就是在数值时区偏移(%z
)中,小时和分钟之间可以选择性地加一个冒号(:
)。但是 Python 默认不会显示这个冒号,所以如果你想要包含它,就需要使用 python-rfc3339 或类似的库。
对于解析 rfc3339 格式,simple-date 可以处理所有格式。但由于它使用的是 Python 的打印功能,所以无法处理上面提到的带冒号的情况。
0
python-rfc3339 对我来说效果很好。
1
这个内容是根据RFC第10页的例子来的。唯一的不同是,我展示的是一个六位数的微秒值,这样做是为了符合Google Drive的时间戳格式。
from math import floor
def build_rfc3339_phrase(datetime_obj):
datetime_phrase = datetime_obj.strftime('%Y-%m-%dT%H:%M:%S')
us = datetime_obj.strftime('%f')
seconds = datetime_obj.utcoffset().total_seconds()
if seconds is None:
datetime_phrase += 'Z'
else:
# Append: decimal, 6-digit uS, -/+, hours, minutes
datetime_phrase += ('.%.6s%s%02d:%02d' % (
us,
('-' if seconds < 0 else '+'),
abs(int(floor(seconds / 3600))),
abs(seconds % 3600)
))
return datetime_phrase