首页 > 解决方案 > Django 和 postgres 时区转换为 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的截图 在此处输入图像描述

标签: djangopostgresqlpython-datetimedatetimeoffset

解决方案


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

如果您在数据库中将它们声明为“没有时区的时间戳”,那么它将不再在进出时转换它们。


推荐阅读