【问题标题】:Django model dateDjango 模型日期
【发布时间】:2014-08-09 23:52:33
【问题描述】:

如何在 Django 模型中只插入日期的周数和年数?因为现在,我只能添加格式为 DD/MM/YYYY 的正常日期吗?

class Status(models.Model):
    date = models.DateField('Date')

【问题讨论】:

  • Django 模型支持 strftime,因此您可以检查 here 以获取您不想要的格式
  • 但我仍然不知道如何更改我的 DateField 的格式。
  • 如果我能正确理解您的问题,您希望存储总周数和相应年份而不是当前周数。对吗?

标签: python django


【解决方案1】:

您必须了解 datefield 存储日期,它是一个对象。因此,无论您想输入哪种格式,都必须将其转换为日期对象。例如:如果你在 ww/yyyy 中插入一个日期:

forms.py

date_value= form.CharField() #When you render this form in template, use JQuery Mask to keep format.
#lets say it will get input like WW/YYYY

views.py

        date_value = datetime.strptime(str(request.POST['date_value'])+'/1', '%W/%Y/%w') #here week count starts from Monday
        new_status= Status()
        new_status.date= date_value
        new_status.save() 

有关 .strptime here 的更多详细信息。

相关问题:here和here

【讨论】:

  • 但我不想在 DD/MM/YYYY 中插入日期,而是以 WW/YYYY 之类的格式插入日期,WW 字符代表一年中的一周。
  • 你能举个例子吗??
  • 我想在我的项目中只使用几周和一年,这将通过 DateField 在数据库中定义。就像我注册一个用户时,我只定义他注册一年中的那一周而不是完整日期。
  • 我会在几次测试后给你反馈。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-10
  • 1970-01-01
  • 2016-04-26
  • 1970-01-01
  • 1970-01-01
  • 2012-11-29
相关资源
最近更新 更多