TimeZone-使非UTC DateTime TimeZone意识到



我有一个可以获得CET DateTime(通过我的API)的情况,我想将其保存在我的django数据库中。

当我这样做时,我总是会收到运行时警告:

datetime.fromtimestamp(last_content_update)

当我添加replace部分时,我不会收到错误,但我的日期不正确(1H偏移):

datetime.fromtimestamp(last_content_update).replace(tzinfo=utc)

知道我如何加载DateTime时区意识?

好的,最后我发现fromtimestamp()采用时区参数!

这样就这样做:

datetime.fromtimestamp(last_content_update, tz=pytz.timezone("Europe/Paris"))

这是文档的链接。

您需要以两个步骤进行此操作:

  1. 首先,让DateTime TimeZone -Aware - 在您的情况下,使用CET(中欧时间)时区。
  2. 第二,在保存之前将日期时间转换为UTC。这是因为Django将数据存储为UTC:

当启用了时区的支持时,Django存储DateTime 数据库中的UTC中的信息...

可以这样完成:

import pytz    
from django.utils import timezone
# Convert the naive datetime into a CET datetime
local_datetime = timezone.make_aware(naive_datetime, pytz.timezone('CET'))
# Convert the CET datetime to UTC
utc_datetime = local_datetime.astimezone(timezone.utc)
# Now it can be saved in the database on a model field
MyDateModel.objects.create(title='Another date model',
                           created=utc_datetime)

最新更新