问题描述
当使用 auto_now_add
这样在Django的 DateTimeField
中保存时间戳时:
When saving timestamp in Django's DateTimeField
using auto_now_add
this way:
creation_timestamp = models.DateTimeField(auto_now_add=True)
该字段的保存时间为毫秒:
the field is saved with miliseconds:
2018-11-20T15:58:44.767594-06:00
我想格式化该格式使其不显示毫秒:
I want to format this to be displayed without miliseconds:
2018-11-20T15:58:44-06:00
但是我能想到的唯一选择不能完全显示我的需求:
But the only option I could come up with does not exactly show what I need:
format =%Y.%m。 %dT%H:%M:%S%z
给我 2018.11.20T15:58:44-0600
如何做我可以根据需要格式化该字段吗?
format="%Y.%m.%dT%H:%M:%S%z"
gives me 2018.11.20T15:58:44-0600
How do I format this field the way I need?
或者我宁愿保存 DateTimeField
而不用毫秒,但是这样做 auto_now_add
允许做这种事情吗?
Alternatively I'd rather save DateTimeField
without milliseconds at all but does auto_now_add
allow to do this sort of thing?
推荐答案
您可以覆盖 DateTimeField
的 value_to_string
方法并在其中添加更改。例如:
You can override DateTimeField
's value_to_string
method and add the changes there. For example:
class CustomDateTimeField(models.DateTimeField):
def value_to_string(self, obj):
val = self.value_from_object(obj)
if val:
val.replace(microsecond=0)
return val.isoformat()
return ''
并在模型中使用它:
created = CustomDateTimeField(auto_now_add=True)
这篇关于在Django中格式化DateTimeField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!