英文:
Django datetime field prints out unsupported operand type error
问题
I have a @property
in my django model which prints out True
or False
based on datetime difference. Even though it works when I am unittesting it I get error
TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date'
class MyModel(models.Model):
...
created_at = models.DateTimeField(auto_now_add=True)
@property
def is_expired(self):
if datetime.now(tz=utc) - self.created_at > timedelta(hours=48):
return True
return False
How do I fix this? Every answer I checked does not help me.
英文:
I have a @property
in my django model which prints out True
or False
based on datetime difference. Even though it works when I am unittesting it I get error
TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date'
class MyModel(models.Model):
...
created_at = models.DateTimeField(auto_now_add=True)
@property
def is_expired(self):
if datetime.now(tz=utc) - self.created_at > timedelta(hours=48):
return True
return False
How do I fix this? Every answer I checked does not help me .
答案1
得分: 1
> 不支持的操作数类型:'datetime.datetime'和'datetime.date'
这表示您不能从datetime.date
中减去datetime.datetime
。在您的情况下,self.created_at
似乎是一个date
,但您对datetime.now()
和timedelta()
的使用表明您实际上想处理datetime
。
因此,解决方案要么是
- 确保
created_at
是一个datetime
,或者 - 将
datetime.now()
更改为date.today()
,并将timedelta(hours=48)
更改为timedelta(days=2)
。
这两种方法的行为略有不同,因此根据物品在两个日历日后到期还是在48小时后到期的情况选择其中之一。
英文:
The traceback error is explaining the problem to you:
> unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date'
This says that you cannot subtract a datetime.datetime
from a datetime.date
. In your case, self.created_at
appears to be a date
but your use of datetime.now()
and timedelta()
suggest that you really want to be dealing with datetime
s.
Therefore, the solution is to either
- make sure that
created_at
is adatetime
, or - change
datetime.now()
todate.today()
and changetimedelta(hours=48)
totimedelta(days=2)
These will behave a little differently so pick one depending on whether things expire after two calendar days or in 48 hours.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论