医生在下面说DateField.auto_now_add https://docs.djangoproject.com/en/4.2/ref/models/fields/#django.db.models.DateField.auto_now_add。 *我用姜戈4.2.1:
首次创建对象时自动将该字段设置为现在。 ...如果您希望能够修改此字段,请设置以下内容而不是auto_now_add=True
:
- For
DateField
: default=date.today
- from datetime.date.today()
- For
DateTimeField
: default=timezone.now
- from django.utils.timezone.now()
所以,我设置时区.now https://docs.djangoproject.com/en/4.2/ref/utils/#django.utils.timezone.now and 日期.今天 https://docs.python.org/3/library/datetime.html#datetime.date.today to datetime
's 日期时间字段() https://docs.djangoproject.com/en/4.2/ref/models/fields/#datetimefield and date1
's 日期字段() https://docs.djangoproject.com/en/4.2/ref/models/fields/#datefield分别,我也设置current_date
返回timezone.now().date()
and current_time
返回timezone.now().time()
to date2
's DateField()
and time
's 时间字段() https://docs.djangoproject.com/en/4.2/ref/models/fields/#timefield分别如下图:
# "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
然后,我设置'America/New_York'
to 时区 https://docs.djangoproject.com/en/4.2/ref/settings/#std-setting-TIME_ZONE in settings.py
如下所示:
# "settings.py"
LANGUAGE_CODE = "en-us"
TIME_ZONE = 'America/New_York' # Here
USE_I18N = True
USE_L10N = True
USE_TZ = True
But, date1
's DateField()
and time
's TimeField()
在 Django Admin 上分别显示 UTC(+0 小时)的日期和时间,如下所示:
接下来我设置'Asia/Tokyo'
to TIME_ZONE
in settings.py
如下所示:
# "settings.py"
LANGUAGE_CODE = "en-us"
TIME_ZONE = 'Asia/Tokyo' # Here
USE_I18N = True
USE_L10N = True
USE_TZ = True
But, date2
's DateField()
and time
's TimeField()
在 Django Admin 上显示 UTC(+0 小时)的日期和时间,如下所示:
那么,如何设置当前正确的日期和时间DateField()
and TimeField()
分别作为默认值TIME_ZONE
在 Django 模型中?
此外,DateField()
and TimeField()
with auto_now https://docs.djangoproject.com/en/4.2/ref/models/fields/#django.db.models.DateField.auto_now or 自动现在添加 https://docs.djangoproject.com/en/4.2/ref/models/fields/#django.db.models.DateField.auto_now_add无法分别保存 UTC(+0 小时)的日期和时间TIME_ZONE
设置。