如何在 Django 模型中通过“TIME_ZONE”将当前正确的日期和时间分别设置为“DateField()”和“TimeField()”作为默认值?

How to set the current proper date and time to "DateField()" and "TimeField()" respectively as a default value by "TIME_ZONE" in Django Models?

提问人:Super Kai - Kazuya Ito 提问时间:6/2/2023 最后编辑:Super Kai - Kazuya Ito 更新时间:6/4/2023 访问量:91

问:

文档在下面DateField.auto_now_add中说。*我使用 Django 4.2.1

在首次创建对象时自动将字段设置为现在。...如果希望能够修改此字段,请设置以下内容而不是:auto_now_add=True

  • 为:DateFielddefault=date.today - from datetime.date.today()
  • 为:DateTimeFielddefault=timezone.now - from django.utils.timezone.now()

因此,我将 timezone.nowdate.today 分别设置为 '的 DateTimeField() 和 '的 DateField(),并且我还设置了分别返回和返回的 's 和 TimeField(),如下所示:datetimedate1current_datetimezone.now().date()current_timetimezone.now().time()date2DateField()time

# "models.py"

from django.db import models
from datetime import date
from django.utils import timezone

def current_date():
    return timezone.now().date()

def current_time():
    return timezone.now().time()

class MyModel(models.Model):
    datetime = models.DateTimeField(default=timezone.now) # Here
    date1 = models.DateField(default=date.today) # Here
    date2 = models.DateField(default=current_date) # Here
    time = models.TimeField(default=current_time) # Here

然后,我设置为TIME_ZONE,如下所示:'America/New_York'settings.py

# "settings.py"

LANGUAGE_CODE = "en-us"

TIME_ZONE = 'America/New_York' # Here

USE_I18N = True

USE_L10N = True

USE_TZ = True

但是,'s 和 's 分别在 Django Admin 上显示 UTC(+0 小时)的日期和时间,如下所示:date1DateField()timeTimeField()

enter image description here

接下来,我设置为 in,如下所示:'Asia/Tokyo'TIME_ZONEsettings.py

# "settings.py"

LANGUAGE_CODE = "en-us"

TIME_ZONE = 'Asia/Tokyo' # Here

USE_I18N = True

USE_L10N = True

USE_TZ = True

但是,'s 和 's 在 Django Admin 上显示 UTC(+0 小时)的日期和时间,如下所示:date2DateField()timeTimeField()

enter image description here

那么,如何在 Django 模型中将当前正确的日期和时间分别设置为 和 作为默认值呢?DateField()TimeField()TIME_ZONE

此外,使用auto_nowauto_now_add无法使用任何设置分别保存UTC(+0小时)的日期和时间。DateField()TimeField()TIME_ZONE

python django datetime django-models 时区

评论


答:

0赞 Ash-Ketchum 6/2/2023 #1

问题是您设置为 .USE_TZTrue

如果设置为 ,无论你的变量设置为什么,Django 都只会使用 UTC。USE_TZTrueTIME_ZONE