如何从DateField对象提取日,月,年? [英] How do I extract day,month,year from a DateField object?
本文介绍了如何从DateField对象提取日,月,年?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含DateField类型的字段'expire_date'的模型.我想定义一个看起来像这样的方法:
I have a model that contains a field 'expire_date' of type DateField. I want to define a method that looks like this:
def get_expire_date_str(self):
return "{0}-{1}-{2}".format(self.expire_date.year, self.expire_date.month, self,expire_date.day)
我浏览了django文档,但仍不确定如何访问此信息.
I looked through the django docs but I'm still not sure how to access this information.
推荐答案
使用datetime模块中的 strftime :>
Use strftime from the datetime module:
date.strftime("%Y-%m-%d")
#=> '1989-12-06'
使用日期时,它更具语义,是最佳实践.
It's more semantic and its a best practice for when working with dates.
以这种方式使用它:
def get_expire_date_str(self):
return self.expire_date.strftime("%Y-%m-%d")
这篇关于如何从DateField对象提取日,月,年?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文