【问题标题】:Python Datetime Showing one day ahead datePython Datetime 显示提前一天的日期
【发布时间】:2021-03-22 13:54:22
【问题描述】:

我遇到了一个奇怪的问题。我有一个 Django 项目,默认使用(美国/丹佛)时区。

我在数据库中获得了几条记录。

id   name   date_create
1    foo    Dec. 8, 2020, 6:15 p.m. 
2    bar    Dec. 1, 2020, 8:28 p.m. 

当我打印上面的记录时,它的行为很奇怪。

>>> print(record_one.date_create.date())
>>> Dec. 9, 2020 
>>> print(record_one.date_create)
>>> Dec. 8, 2020, 6:15 p.m.

>>> print(record_two.date_create.date())
>>> Dec. 2, 2020
>>> print(record_one.date_create)
>>> Dec. 1, 2020, 8:28 p.m.

我正在使用 python 3.5 和 Django2

Django 设置

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'America/Denver'

USE_I18N = True

USE_L10N = True

USE_TZ = True

【问题讨论】:

  • 您使用的是哪个数据库?
  • @ArakkalAbu postgresql on aws 服务器
  • 我几乎可以肯定 record_one.date_create 将返回 DateTime 对象的 __str__ 表示,它看起来像 2020-12-11 01:00:00+00:00。所以,最后一个 +00.00 表示重新调整的时间是 UTC 而不是 TIME_ZONE
  • afaik,Django 将在 UTC 中保存时间(恕我直言,这是最佳做法),并且会在需要时转换为 XYZ 时区。

标签: python django timezone pytz


【解决方案1】:

这是the documentation 中解释的预期行为:

当 USE_TZ 为 True 时,这是 Django 用于在模板中显示日期时间并解释在表单中输入的日期时间的默认时区。

因此,从数据库中检索的值是 tzinfo 设置为 UTC 的感知日期时间。然后模板标签可以使用astimezone(通过timezone.template_localtime -> timezone.localtime)进行转换。但是,您在字段值上调用日期。

要模拟模板行为,我们可以执行以下操作:

from django.utils.timezone import template_localtime
import datetime
import pytz
denver = pytz.timezone("America/Denver")
utc = pytz.timezone("UTC")
denver_dt = datetime.datetime(2020, 12, 8, 18, 15, microsecond=0, tzinfo=denver)
utc_dt = denver_dt.astimezone(utc)
template_localtime(utc_dt)
Out[9]: datetime.datetime(2020, 12, 8, 18, 15, tzinfo=<DstTzInfo 'America/Denver' MST-1 day, 17:00:00 STD>)
template_localtime(utc_dt).date()
Out[10]: datetime.date(2020, 12, 8)

所以你的变量:

print(template_localtime(record_one.date_create).date())

【讨论】:

  • 您将TIME_ZONE 设置(OP 引用)与作为DATABASES 设置一部分的特定于数据库的'TIME_ZONE 混淆了(这是您引用的文档)。跨度>
  • 我确实做到了。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-10
  • 2017-12-29
  • 1970-01-01
  • 2021-05-06
相关资源
最近更新 更多