在Django模型中更改日期格式 [英] Change Date format in Django model
问题描述
在Django模型中,我有一个名为生日的日期字段和一个名为寿命的属性。
字段
出生日期= models.DateField(blank = True,null = True)
财产
@财产
def寿命(自我):
返回'%s-present'%self.birthdate
当前寿命以 yyyy-mm-dd格式返回日期。
如何将日期格式更改为 mm / dd / yyyy?
p>我知道如何在带有过滤器的Django模板中执行此操作,但想查看是否可以在Django模型中使用类似的过滤器。
感谢您的反馈。
要完全控制,请使用 strftime
:
@property
def life span(self):
返回'%s-present'%self.birthdate.strftime('%m /%d /%Y')
strftime
没有Django的日期
filter可以,因此,如果要使用其中之一,可以将过滤器作为函数调用:
来自django.template.defaultfilters导入日期
@ property
def寿命(自):
返回'%s-present'%date(self.birthdate, n / j / Y)
这将省略前导零,并允许您使用 DATE_FORMAT
设置变量或其他预定义选项。
I have a date field called "birthdate" and property called "lifespan" in a django model.
Field
birthdate = models.DateField(blank=True, null=True)
Property
@property
def lifespan(self):
return '%s - present' % self.birthdate
Currently lifespan returns the date in the "yyyy-mm-dd" format.
How can I changed this date format to "mm/dd/yyyy"?
I know how to do it in a django template with a filter but wanted to see if there was a similar "filter" that I can use in a Django model.
I appreciate the feedback.
For full control, use strftime
:
@property
def lifespan(self):
return '%s - present' % self.birthdate.strftime('%m/%d/%Y')
strftime
doesn't have all the formatting options that Django's date
filter does, so if you want one of those you could call the filter as a function:
from django.template.defaultfilters import date
@property
def lifespan(self):
return '%s - present' % date(self.birthdate, "n/j/Y")
That would omit the leading zeros, and would let you use your DATE_FORMAT
settings variable or other predefined options.
这篇关于在Django模型中更改日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!