获取时区感知日期时间

Get timezone aware datetime

我将如何执行以下操作来获取 UTC 日期时间对象,这样 django 就不会抱怨 /Library/Python/2.7/site-packages/django/db/models/fields/__init__.py:808: RuntimeWarning: DateTimeField received a naive datetime (2015-02-11 00:00:00) while time zone support is active.

>>> from django.utils import timezone
>>> timezone.date(2014,1,1)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'module' object has no attribute 'date'

假设您的输入是一个没有时区信息的字符串,只需将文字 "Z" 附加到您的字符串即可。这表示与 UTC 时间的偏移量为零。

以您的示例为例,您应该使用 datetime 并指定 tzinfo 参数:

timezone.datetime(2014, 1, 1, tzinfo=timezone.UTC())

您可能还对 Django 的 make_aware 功能感兴趣:

https://docs.djangoproject.com/en/dev/ref/utils/#django.utils.timezone.make_aware