【问题标题】:How can I get the timezone aware date in django?如何在 django 中获取时区感知日期?
【发布时间】:2015-02-06 18:07:33
【问题描述】:

我在 python django 中使用 delorean 进行日期时间计算。

http://delorean.readthedocs.org/en/latest/quickstart.html

这是我正在使用的:

now = Delorean(timezone=settings.TIME_ZONE).datetime
todayDate = now.date()

但我收到此警告:

RuntimeWarning: DateTimeField start_time received a naive datetime (2014-12-09 00:00:00) while time zone support is active.

我想知道如何让它知道。

我也试过了:

todayDate = timezone.make_aware(now.date(), timezone=settings.TIME_ZONE)

然后我明白了:

AttributeError: 'datetime.date' object has no attribute 'tzinfo'

【问题讨论】:

标签: python django datetime timezone


【解决方案1】:

目前尚不清楚您是要以 date 对象还是 datetime 对象结束,因为 Python 没有“时区感知日期”的概念。

要获取与当前时区中的当前时间对应的date 对象,您可以使用:

# All versions of Django
from django.utils.timezone import localtime, now
localtime(now()).date()

# Django 1.11 and higher
from django.utils.timezone import localdate
localdate()

也就是说:您将获得 UTC 格式的当前时区感知 datetime;您正在将其转换为本地时区(即TIME_ZONE);然后从中获取日期。

如果你想获得一个datetime 对应于当前时区当前日期的 00:00:00 的对象,你可以使用:

# All versions of Django
localtime(now()).replace(hour=0, minute=0, second=0, microsecond=0)

# Django 1.11 and higher
localtime().replace(hour=0, minute=0, second=0, microsecond=0)

基于此和your other question,我认为您对 Delorean 软件包感到困惑。我建议坚持使用 Django 和 Python 的日期时间功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-21
    • 2019-01-18
    • 2013-07-18
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 2017-06-26
    相关资源
    最近更新 更多