Django 和 postgres 时区转换为 UTC

Django and postgres timezone converts to UTC

在我的应用程序中,用户提供他们的时区并保存。

所以我手动处理时区转换

    local_time = datetime.now(tz=ZoneInfo(self.time_zone))
      #time_zone is "US/Pacific"

然而,当我保存到 postgres 时,它仍然被转换回 UTC 0。

在设置中:

    # TIME_ZONE = 'UTC' #commented out
    USE_L10N = False
    USE_TZ = False

那也不行,所以我做了一个中间件:

    # CUSTOM TIME ZONE HANDLER
    class TimezoneMiddleware:
        def __init__(self, get_response):
            self.get_response = get_response

        def __call__(self, request):
            time_zone = "US/Pacific" #will be changed to a fn call
            if time_zone:
                timezone.activate(pytz.timezone(time_zone))
            else:
                timezone.deactivate()
            return self.get_response(request)

在设置中:

    MIDDLEWARE = [
        ...
        'time_log_app.utils.TimezoneMiddleware',
    ]

这是插入数据的函数:

    def insert_data_time_log(user, data):
       #this is the data obj before insertion

    {
    'clock_out': datetime.datetime(2021, 8, 21, 8, 16, 30, 420947, tzinfo=zoneinfo.ZoneInfo(key='US/Pacific')), 
    'hourly_rate': 50
    }
        ...
        TimeLog.objects.create(pk=user, **data)

型号:

    class TimeLog(models.Model):
        clock_in = models.DateTimeField(null=True, blank=True)
        clock_out = models.DateTimeField(null=True, blank=True)
        hourly_rate = models.DecimalField(max_digits=20, decimal_places=2, null=True)
        employee_type = models.CharField(max_length=200, null=True)

那也不行!!

我在这里几乎没有希望,我做错了什么??

或者我应该为此使用原始 sql?

这是postgres的截图

PostgreSQL 始终以 UTC 格式存储 timestamptz,但在将它们发回给您时将它们转换为您的会话时区(并且当它从您那里收到它们时,如果它们缺少明确的时区,它将解释为在您的会话时区中).如果您想在与您的会话时区不同的时区查看它们,您可以更改您的会话时区 set timezone='US/Pacific' 或者您可以在它返回时使用 python 转换它。

如果您在数据库中将它们声明为 'timestamp without time zone',那么它将不再在进出的途中转换它们。