'datetime.date'对象没有属性'date'

dem*_*mux 7 django datetime django-models

这段代码:

import datetime
d_tomorrow = datetime.date.today() + datetime.timedelta(days=1)

class Model(models.Model):
    ...
    timeout = models.DateTimeField(null=True, blank=True, default=d_tomorrow)
    ...
Run Code Online (Sandbox Code Playgroud)

导致此错误:

'datetime.date' object has no attribute 'date'
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

mip*_*adi 13

d_tomorrow由Django ORM预期有一个date属性(显然),但没有.

无论如何,您可能希望使用可调用的默认日期; 否则,每个模型的默认日期将相对于模型类初始化的时间为"明天",而不是模型创建的时间.你可以试试这个:

import datetime

def tomorrow():
  return datetime.date.today() + datetime.timedelta(days=1)

class Model(models.Model):
  timeout = models.DateTimeField(null=True, blank=True, default=tomorrow)
Run Code Online (Sandbox Code Playgroud)


dem*_*mux 3

问题解决了:

from datetime import datetime, time, date, timedelta
def tomorrow():
    d = date.today() + timedelta(days=1)
    t = time(0, 0)
    return datetime.combine(d, t)
Run Code Online (Sandbox Code Playgroud)

models.DateTimeField期望值为datetime.datetime,而不是datetime.date

2015 年更新:

箭头使这一切变得更加直接。

Arrow 是一个 Python 库,它提供了一种合理的、人性化的方法来创建、操作、格式化和转换日期、时间和时间戳。它实现并更新了日期时间类型,填补了功能空白,并提供了支持许多常见创建场景的智能模块 API。简而言之,它可以帮助您使用更少的导入和更少的代码来处理日期和时间。

Arrow 深受 moment.js 和 requests 的启发。