【问题标题】:django compare date with datedjango比较日期和日期
【发布时间】:2012-09-13 22:46:34
【问题描述】:

我试图拒绝导入日期小于已导入日期的行。

timelimit = Operation.objects.filter(account = 3).aggregate(Max('date'))
for row in csv.reader(reencode(f), delimiter=';', quotechar='"')
  if row != []:
    if row[0]>timelimit:
      operation.date=row[0]

行看起来像: 2012-01-12,某事,0,某事2

当然比较 row[0]>timelimit 是错误的 - 但什么是正确的?

【问题讨论】:

    标签: django date comparison


    【解决方案1】:
        #this will convert your string("2012-01-12") to a datetime object
    
        from datetime import datetime
        >>> x = datetime.strptime(row[0], "%Y-%m-%d")
        >>> x
        >>> datetime.datetime(2012, 1, 12, 0, 0)
    

    然后你也可以像这样在日期时间对象中转换时间限制:

        timelimit = datetime(2011, 10, 10)
    

    然后比较这两者是微不足道的:

        x > timelimit
    

    【讨论】:

    • 嗯,不知道怎么赋值 operation.date=row[0] (其中 operation.date 是 ModelField.DateTime
    • 您将 row[0] 转换为 datetime 对象,就像我的示例中一样(x = datetime.datetime(2012,1,12,0,0),然后在行上使用 .date()像这样: operation.date = x.date().
    • 它不起作用:x > timelimit Traceback(最近一次调用最后一次):文件“”,第 1 行,在 类型错误:无法将 datetime.datetime 与 dict 进行比较
    • 将时间限制转换为日期时间对象。我在上面的例子中有它。然后您将能够比较两个日期时间对象。
    • timelimit is a dict ;D 所以我必须使用 timelimit["date__max"]... 但它是 date 也不是 datetime... 如何转换?
    猜你喜欢
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 2016-08-25
    • 1970-01-01
    • 2020-12-16
    • 2018-09-25
    • 1970-01-01
    相关资源
    最近更新 更多