django.utils.timezone.now()、datetime.datetime.now() 和 pytz.timezone 出现奇怪的输出

Experiencing odd output from django.utils.timezone.now(), datetime.datetime.now() and pytz.timezone

我在尝试在 UTC 和特定时区之间进行转换时遇到了奇怪的行为。我希望有人能解释为什么我会看到这种行为,以及获取时区信息的更多 "correct" 方式可能是什么。

代码:

import pytz
import datetime
from django.utils import timezone

print(timezone.now())
print(pytz.utc.localize(datetime.datetime.now()))
print('\n')

def get_local_and_utc_date_ranges(days=1500, days_ago=2, local_timezone="America/Asuncion"):
    seller_timezone = pytz.timezone(local_timezone)
    utc_timezone = pytz.utc

    seller_today = timezone.now().astimezone(seller_timezone)
    seller_days_ago = seller_today - timezone.timedelta(days=days_ago)

    local_date_end = seller_days_ago.replace(hour=23, minute=59, second=59, microsecond=999999)
    local_date_start = (local_date_end - timezone.timedelta(days=days)).replace(hour=0, minute=0, second=0, microsecond=0)

    utc_date_end = local_date_end.astimezone(utc_timezone)
    utc_date_start = local_date_start.astimezone(utc_timezone)

    date_ranges = {
        "local_date_end": local_date_end,
        "local_date_start": local_date_start,
        "utc_date_end": utc_date_end,
        "utc_date_start": utc_date_start,
    }

    return date_ranges


def get_utc_and_local_date_ranges(days=1500, days_ago=2, local_timezone='America/Asuncion'):
    seller_timezone = pytz.timezone(local_timezone)
    utc_timezone = pytz.utc

    utc_today = datetime.datetime.utcnow()
    utc_days_ago = utc_today - datetime.timedelta(days=days_ago)

    local_date_end = seller_timezone.localize(utc_days_ago).replace(
        hour=23, minute=59, second=59, microsecond=999999
    )
    local_date_start = (local_date_end - datetime.timedelta(days=days)).replace(
        hour=0, minute=0, second=0, microsecond=0
    )
    utc_date_end = local_date_end.astimezone(utc_timezone)
    utc_date_start = local_date_start.astimezone(utc_timezone)

    date_ranges = {
        'local_date_end': local_date_end,
        'local_date_start': local_date_start,
        'utc_date_end': utc_date_end,
        'utc_date_start': utc_date_start,
    }

    return date_ranges



days = 1500
days_ago = 2

dates = get_local_and_utc_date_ranges(days=days, days_ago=days_ago)
dates2 = get_utc_and_local_date_ranges(days=days, days_ago=days_ago)


print('dates1:')
print('local_date_start:', dates['local_date_start'])
print('local_date_end:', dates['local_date_end'])
print('utc_date_start:', dates['utc_date_start'])
print('utc_date_end:', dates['utc_date_end'])
print('\n')

print('dates2:')
print('local_date_start:', dates2['local_date_start'])
print('local_date_end:', dates2['local_date_end'])
print('utc_date_start:', dates2['utc_date_start'])
print('utc_date_end:', dates2['utc_date_end'])
print('\n')

输出:

2019-03-25 18:57:55.929908+00:00
2019-03-25 18:57:55.930005+00:00


dates1:
local_date_start: 2015-02-12 00:00:00-04:00
local_date_end: 2019-03-23 23:59:59.999999-04:00
utc_date_start: 2015-02-12 04:00:00+00:00
utc_date_end: 2019-03-24 03:59:59.999999+00:00


dates2:
local_date_start: 2015-02-12 00:00:00-03:00
local_date_end: 2019-03-23 23:59:59.999999-03:00
utc_date_start: 2015-02-12 03:00:00+00:00
utc_date_end: 2019-03-24 02:59:59.999999+00:00

请注意不一致的 UTC 偏移量(该特定时区在 3 月 23 日切换为夏令时)。但是当我尝试使用以下代码复制问题时:

import pytz 
import datetime 
from django.utils import timezone 

now1 = timezone.now() - datetime.timedelta(days=2)
now2 = pytz.utc.localize(datetime.datetime.now()) - datetime.timedelta(days=2)

seller_timezone = pytz.timezone('America/Asuncion')

print(now1.astimezone(seller_timezone).replace(
        hour=23, minute=59, second=59, microsecond=999999
    ))
print(now2.astimezone(seller_timezone).replace(
        hour=23, minute=59, second=59, microsecond=999999
    ))

输出正确:

2019-03-23 23:59:59.999999-03:00
2019-03-23 23:59:59.999999-03:00

我希望有人能理解为什么会发生这种行为,如果是这样,我该如何避免这种不一致。

您的 get_local_and_utc_date_ranges() 函数产生了不正确的结果,因为它使用本地化时间进行日期时间算术运算(即减去 timedelta),这是行不通的。

seller_today = timezone.now().astimezone(seller_timezone)
seller_days_ago = seller_today - timezone.timedelta(days=days_ago)

这在 datetime module documentation 中注明:

As for addition, the result [of subtracting a timedelta] has the same tzinfo attribute as the input datetime, and no time zone adjustments are done even if the input is aware.

这在pytz documentation中也有注明:

If you perform date arithmetic on local times that cross DST boundaries, the result may be in an incorrect timezone.

pytz 提供修复:

A normalize() method is provided to correct this.

所以你可以使用:

seller_days_ago = seller_timezone.normalize(seller_today - timezone.timedelta(days=days_ago))
...
local_date_start = seller_timezone.normalize(local_date_end - timezone.timedelta(days=days)).replace(hour=0, minute=0, second=0, microsecond=0)

但是,文档 also notes that:

The preferred way of dealing with times is to always work in UTC.

所以更好的解决方案是只在 UTC 中进行算术运算:

utc_today = datetime.datetime.utcnow()
utc_date_end = utc_today - datetime.timedelta(days=days_ago)
utc_date_start = utc_date_end - datetime.timedelta(days=days)

local_date_end = seller_timezone.localize(utc_date_end).replace(hour=23, minute=59, second=59, microsecond=999999)
local_date_start = seller_timezone.localize(utc_date_start).replace(hour=0, minute=0, second=0, microsecond=0)