Django中DateTimeField过滤器的问题

时间:2014-05-01 00:57:21

标签: python mysql django django-models

请帮助我) 我有错误“[u”'data_date'值的格式无效。它必须是YYYY-MM-DD HH:MM [:ss [.uuuuuu]] [TZ]格式。“]”并且不知道如何解决它。

my models.py

class Data(models.Model):
    main = models.ForeignKey(Main)
    user = models.CharField(max_length=200)
    description = models.TextField()
    data_date = models.DateTimeField(['%Y-%m-%d %H:%M'])
    priority = models.CharField(max_length=1)
    end_date = models.DateTimeField(['%Y-%m-%d %H:%M'])
    def __unicode__(self):
         return self.description
    def was_published_recently(self):
        return self.data_date >= timezone.now() - datetime.timedelta(days=1)

my views.py

def index(request, onsuccess='/', onfail='/login/'):       
    today = date.today()
    data_data=timezone.now()
    formatted_datetime = formats.date_format(data_data, "SHORT_DATETIME_FORMAT")
    problems_filter = Data.objects.filter(main_id=1).filter(data_date__range=['data_date', 'end_date']).order_by('-data_date').order_by('priority')[:101]
#    problems_filter = Data.objects.filter(main_id=1).order_by('-data_date').order_by('priority')[:10]

当我使用推荐字符串时,它工作正常。

示例格式:  28 | 1 |管理员|嗨| 2014-05-01 00:41:00 | 2 | 2014-06-01 00:00:00

1 个答案:

答案 0 :(得分:2)

您似乎忽略了输入字符串中的seconds部分以转换为datetime

data_date = models.DateTimeField( ['%Y-%m-%d %H:%M'] )
end_date  = models.DateTimeField( ['%Y-%m-%d %H:%M'] )

+---------------------+-------------------+----------------+
| input_date_string   | its_format        | what_you_tried |
+---------------------+-------------------+----------------+
| 2014-05-01 00:41:00 | %Y-%m-%d %H:%M:%S | %Y-%m-%d %H:%M |
| 2014-06-01 00:00:00 | %Y-%m-%d %H:%M:%S | %Y-%m-%d %H:%M |
+---------------------+-------------------+----------------+

相应更改data_dateend_date字段。

data_date = models.DateTimeField( ['%Y-%m-%d %H:%M:%S'] )
end_date  = models.DateTimeField( ['%Y-%m-%d %H:%M:%S'] )

请参阅DATETIME_INPUT_FORMATS

默认值:

(  
    '%Y-%m-%d %H:%M:%S',     # '2006-10-25 14:30:59'  
    '%Y-%m-%d %H:%M:%S.%f',  # '2006-10-25 14:30:59.000200'  
    '%Y-%m-%d %H:%M',        # '2006-10-25 14:30'  
    '%Y-%m-%d',              # '2006-10-25'  
    '%m/%d/%Y %H:%M:%S',     # '10/25/2006 14:30:59'  
    '%m/%d/%Y %H:%M:%S.%f',  # '10/25/2006 14:30:59.000200'  
    '%m/%d/%Y %H:%M',        # '10/25/2006 14:30'  
    '%m/%d/%Y',              # '10/25/2006'  
    '%m/%d/%y %H:%M:%S',     # '10/25/06 14:30:59'  
    '%m/%d/%y %H:%M:%S.%f',  # '10/25/06 14:30:59.000200'  
    '%m/%d/%y %H:%M',        # '10/25/06 14:30'  
    '%m/%d/%y',              # '10/25/06'  
)