【发布时间】:2012-11-01 21:44:02
【问题描述】:
我正在使用 Django。
在设置中:
TIME_ZONE = 'Europe/Copenhagen'
USE_TZ = True
由于 DST,2013 年 3 月 31 日时钟会跳过一个小时。 01:59 转到 03:00
我的观点:
日期和时间以当地时间给出。我希望这些以 UTC 格式插入。
以下代码正确保存为 UTC,但给出 RuntimeWarning: DateTimeField received a naive datetime
the_date = datetime.datetime(2013, 3, 31, 1, 59)
hit = hits(date= the_date); hit.save(); # Correctly saved as 00:59:00
the_date = datetime.datetime(2013, 3, 31, 3, 1)
hit = hits(date= the_date); hit.save(); # Correctly saved as 01:01:00
我想我可以通过知道日期时间来避免警告。它确实避免了警告,但现在转换是错误的。
tz = timezone(settings.TIME_ZONE)
the_date = datetime.datetime(2013, 3, 31, 3, 1, tzinfo = tz)
hit = hits(date= the_date); hit.save(); # Incorrectly saved as 02:01:00
以下工作,没有运行时错误:
I have installed pytz.
the_date = local_tz.localize(datetime.datetime(2013, 3, 31, 3, 1))
回答我的问题:
我知道 tzinfo 不起作用,因为它没有考虑夏令时。好吧,我不会用它。但是当以下似乎起作用时,我感到困惑:
the_date = datetime.datetime.now(local_tz)
这在冬季(减去 1 小时得到 utc)和我将计算机系统时间更改为夏天的日期(减去 2 小时得到 utc)时都正确插入为 utc。
我的问题:
.now(local_tz) 有效还是我测试错了?为什么这与 tzinfo = tz 不同?还是我使用 tzinfo 错误?
【问题讨论】:
标签: python django timezone pytz