在 Python 中生成 RFC 3339 时间戳 [英] Generate RFC 3339 timestamp in Python

查看:114
本文介绍了在 Python 中生成 RFC 3339 时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Python 中生成 RFC 3339 UTC 时间戳.到目前为止,我已经能够做到以下几点:

<预><代码>>>>d = 日期时间.日期时间.现在()>>>打印 d.isoformat('T')2011-12-18T20:46:00.392227

我的问题是设置 UTC 偏移量.

根据docs,classmethod datetime.now([tz]),采用可选的 tz 参数,其中 tz 必须是类 tzinfo 子类datetime.tzinfo 的实例是时区信息对象的抽象基类.

这就是我迷路的地方 - 为什么 tzinfo 是一个抽象类,我应该如何实现它?


(注意:在 PHP 中它就像 timestamp = date(DATE_RFC3339); 一样简单,这就是为什么我不明白为什么 Python 的方法如此复杂...)

解决方案

UPDATE 2021

在 Python 3.2 中 timezone 被添加到 datetime 模块中,允许您轻松地为 UTC 分配时区.

<预><代码>>>>导入日期时间>>>n = datetime.datetime.now(datetime.timezone.utc)>>>n.isoformat()'2021-07-13T15:28:51.818095+00:00'

上一个答案:

时区很痛苦,这可能是他们选择不将它们包含在日期时间库中的原因.

试试 pytz,它有你要找的 tzinfo:http://pytz.sourceforge.net/

您需要首先创建 datetime 对象,然后应用如下所示的时区,然后您的 .isoformat() 输出将根据需要包含 UTC 偏移量:

d = datetime.datetime.utcnow()d_with_timezone = d.replace(tzinfo=pytz.UTC)d_with_timezone.isoformat()

<块引用>

'2017-04-13T14:34:23.111142+00:00'

或者,只使用 UTC,然后抛出一个Z";(对于 Zulu 时区)在末尾标记时区"作为 UTC.

d = datetime.datetime.utcnow() # <-- 获取UTC时间打印 d.isoformat("T") + "Z";

<块引用>

'2017-04-13T14:34:23.111142Z'

I'm trying to generate an RFC 3339 UTC timestamp in Python. So far I've been able to do the following:

>>> d = datetime.datetime.now()
>>> print d.isoformat('T')
2011-12-18T20:46:00.392227

My problem is with setting the UTC offset.

According to the docs, the classmethod datetime.now([tz]), takes an optional tz argument where tz must be an instance of a class tzinfo subclass, and datetime.tzinfo is an abstract base class for time zone information objects.

This is where I get lost- How come tzinfo is an abstract class, and how am I supposed to implement it?


(NOTE: In PHP it's as simple as timestamp = date(DATE_RFC3339);, which is why I can't understand why Python's approach is so convoluted...)

解决方案

UPDATE 2021

In Python 3.2 timezone was added to the datetime module allowing you to easily assign a timezone to UTC.

>>> import datetime
>>> n = datetime.datetime.now(datetime.timezone.utc)
>>> n.isoformat()
'2021-07-13T15:28:51.818095+00:00'

previous answer:

Timezones are a pain, which is probably why they chose not to include them in the datetime library.

try pytz, it has the tzinfo your looking for: http://pytz.sourceforge.net/

You need to first create the datetime object, then apply the timezone like as below, and then your .isoformat() output will include the UTC offset as desired:

d = datetime.datetime.utcnow()
d_with_timezone = d.replace(tzinfo=pytz.UTC)
d_with_timezone.isoformat()

'2017-04-13T14:34:23.111142+00:00'

Or, just use UTC, and throw a "Z" (for Zulu timezone) on the end to mark the "timezone" as UTC.

d = datetime.datetime.utcnow() # <-- get time in UTC
print d.isoformat("T") + "Z"

'2017-04-13T14:34:23.111142Z'

这篇关于在 Python 中生成 RFC 3339 时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆