Django datetime field prints out unsupported operand type error.

huangapple go评论66阅读模式
英文:

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

因此,解决方案要么是

  1. 确保created_at是一个datetime,或者
  2. 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 datetimes.

Therefore, the solution is to either

  1. make sure that created_at is a datetime, or
  2. change datetime.now() to date.today() and change timedelta(hours=48) to timedelta(days=2)

These will behave a little differently so pick one depending on whether things expire after two calendar days or in 48 hours.

huangapple
  • 本文由 发表于 2023年3月31日 22:40:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75899810.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定