gpt4 book ai didi

python - Django make_aware 用法

转载 作者:太空宇宙 更新时间:2023-11-03 11:21:22 24 4
gpt4 key购买 nike

Django docs说:

The pytz.NonExistentTimeError exception is raised if you try to make value aware during a DST transition such that the time never occurred (when entering into DST). Setting is_dst to True or False will avoid the exception by moving the hour backwards or forwards by 1 respectively. For example, is_dst=True would change a non-existent time of 2:30 to 1:30 and is_dst=False would change the time to 3:30.

所以我希望时间根据 is_dst 的值向前或向后移动一位。

但根据我的测试,时区正在改变,而不是时间。我是否误解了 Django 文档或者这是一个错误?

我测试了以下内容:

import pytz
import datetime
from django.utils.timezone import make_aware

tz = pytz.timezone('America/Sao_Paulo')
dt = datetime.datetime(2017, 10, 15 ,0 ,0)
print(make_aware(dt, tz)) # NonExistentTimeError
print(make_aware(dt, tz, True)) # 2017-10-15 00:00:00-02:00
print(make_aware(dt, tz, False)) # 2017-10-15 00:00:00-03:00

2017-10-15 是 DST 在 America/Sao_Paulo 时区开始的时间,因此当时钟到达 00:00 时,它应该跳到 01:00。 make_aware 方法返回的日期时间不存在。

最佳答案

来自source code我们可以看到 Django 只是包装了 pytz。因此,如果这里出现问题,要么是 pytz 错误,要么是 Django 文档错误。

现在,由于您向 localize() 传递了一个不存在的时间,它必须更改挂钟时间或 tzinfo 才能返回一个有效的时间。虽然pytz documentation在这一点上不是很精确,它的契约(Contract)似乎总是返回一个与传入的挂钟时间相同的 datetime。这是有道理的,尤其是当你考虑并行时间不明确的情况。

所以我认为 Django 文档说的是错误的:

Setting is_dst to True or False will avoid the exception by moving the hour backwards or forwards by 1 respectively. For example, is_dst=True would change a non-existent time of 2:30 to 1:30 and is_dst=False would change the time to 3:30.

但请注意,实际时间与文档描述的时间相同:

tz = pytz.timezone('America/Sao_Paulo')
dt = datetime.datetime(2017, 10, 15, 0)
dt_plus_one = datetime.datetime(2017, 10, 15, 1)
dt_minus_one = datetime.datetime(2017, 10, 14, 23)

make_aware(dt, tz, True) == make_aware(dt_minus_one, tz) # True
make_aware(dt, tz, False) == make_aware(dt_plus_one, tz) # True

请考虑filing a ticket关于这个!

关于python - Django make_aware 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42399438/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com