替换 "tzinfo" 并打印为本地时间修改六分钟

Replace "tzinfo" and print with localtime amends six minutes

我正在创建一个没有时区的 DataTimeField。很快我正在编辑这个 TZ "manually",然后要求用本地 TZ 读取值。六分钟见最终结果修正!

逻辑:

>>> import datetime
>>> from django.utils import timezone
>>> test = datetime.datetime(2016, 9, 28, 10, 10, 10)
datetime.datetime(2016, 9, 28, 10, 10, 10)

>>> test = teste.replace(tzinfo=pytz.timezone('America/Sao_Paulo'))
datetime.datetime(2016, 9, 28, 10, 10, 10, tzinfo=<DstTzInfo 'America/Sao_Paulo' LMT-1 day, 20:54:00 STD>)

>>> timezone.activate(pytz.timezone('America/Sao_Paulo'))
>>> timezone.localtime(test)
datetime.datetime(2016, 9, 28, 10, 16, 10, tzinfo=<DstTzInfo 'America/Sao_Paulo' BRT-1 day, 21:00:00 STD>)

注意:这个想法是分两个阶段发生的。首先,我想在创建 TimeZone 时继续坐在板凳上。然后我想用用户的时区显示给用户。在这种情况下,两个用户都是同一地区。

对不起我的英语


根据@user6897474 的回复并付诸实践,我得到了这个解决方案:

我在保存之前获取 POST 和序列化文件的日期时间,请执行以下操作:

class CheckControllerSerializer(serializers.ModelSerializer):
    def create(self, validated_data):
        datetime = validated_data['datetime'].replace(tzinfo=None)
        validated_data['datetime'] = pytz.timezone('America/Sao_Paulo').localize(datetime)

        return super(CheckControllerSerializer, self).create(validated_data)

替换tzinfo=None,我保证你不会遇到以下错误的问题:

Not naive datetime (tzinfo is already set)

使用timezone.localize代替datetime.replace

>>> test = datetime.datetime(2016, 9, 28, 10, 10, 10)
>>> test = pytz.timezone('America/Sao_Paulo').localize(test)
datetime.datetime(2016, 9, 28, 10, 10, 10, tzinfo=<DstTzInfo 'America/Sao_Paulo' BRT-1 day, 21:00:00 STD>)

>>> timezone.activate(pytz.timezone('America/Sao_Paulo'))
>>> timezone.localtime(test)
datetime.datetime(2016, 9, 28, 10, 10, 10, tzinfo=<DstTzInfo 'America/Sao_Paulo' BRT-1 day, 21:00:00 STD>)

参考:

  1. pytz.localize vs datetime.replace

  2. datetime object, when rendered to Django template, was always 6 minutes off