gpt4 book ai didi

python - Django 模型 DateTimeField 设置 auto_now_add 格式或修改序列化器

转载 作者:行者123 更新时间:2023-11-28 22:36:30 24 4
gpt4 key购买 nike

我的模型中有这个字段:

createdTime = models.DateTimeField(_('Creation date'), help_text=_('Date of the creation'),
auto_now_add=True, blank=True)

并以这种格式保存:

2016-05-18T15:37:36.993048Z

所以我想将它转换成这种格式 DATE_INPUT_FORMATS = ('%d-%m-%Y %H:%M:S') 但我不知道在哪里做。

我有一个简单的序列化器类,我可以覆盖它来修改格式吗?或者创建一个 get_date() 模型方法?

class ObjectSerializer(serializers.ModelSerializer):
"""
Serializer for object.
"""
class Meta:
model = Object

我的设置:

DATETIME_FORMAT = '%d-%m-%Y %H:%M:%S'

USE_I18N = True

USE_L10N = False

USE_TZ = False

最佳答案

在您的 settings.py 中按照指定设置 DATETIME_FORMAT here .

The default formatting to use for displaying datetime fields in any part of the system. Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead

settings.py 的日期部分之后应该如下所示:

DATETIME_FORMAT = '%d-%m-%Y %H:%M:%S' 
USE_L10N = False
USE_TZ = False # if you plan to disable timezone support

或者,您可以通过以下方式在检索后手动更改格式:

import datetime

datetime_str = '2016-05-18T15:37:36.993048Z'
old_format = '%Y-%m-%dT%H:%M:%S.%fZ'
new_format = '%d-%m-%Y %H:%M:%S'

new_datetime_str = datetime.datetime.strptime(datetime_str, old_format).strftime(new_format)
print(new_datetime_str)
#'18-05-2016 15:37:36'

此转换可以作为您建议的 get_date() 方法添加到您的序列化程序或模型中

关于python - Django 模型 DateTimeField 设置 auto_now_add 格式或修改序列化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37346573/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com