0

I would like to create a column called "date_expiration" in my models.py that takes the current time and adds four days to it. The following code results in an unsupported operand type(s) for +: 'builtin_function_or_method' and 'datetime.timedelta' because I'm not expliciltly calling the utcnow with parenthesis().

Here is my class with the above error:

class Submission(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    uri = db.Column(db.String(100), nullable=False)
    uri_name = db.Column(db.String(60), nullable=False)
    reviewer = db.Column(db.String(50), nullable=False)
    url = db.Column(db.String(200), nullable=False)
    date_submission = db.Column(db.DateTime, nullable=False, 
        default=datetime.datetime.utcnow)
    date_expiration = db.Column(db.DateTime, nullable=False, default= 
        (datetime.datetime.utcnow + datetime.timedelta(days=4)))
    submission_description = db.Column(db.Text, nullable=False)

What is the proper way to set the date_expiration column?

  • 2
    Have a look at the options laid out in this SO answer: https://stackoverflow.com/a/33532154/42346 – mechanical_meat Aug 15 '21 at 13:07
  • What database are you using? – snakecharmerb Aug 15 '21 at 13:09
  • 1
    Warning - there is a typo in your code: defualt – Kate Aug 15 '21 at 13:39
  • I'm using SQLite right now, plan is to swap it out later closer to deployment – Adventure-Knorrig Aug 16 '21 at 06:54
  • The options in that SO answer did help some but I didn't see much about setting a future date/time as a result of adding to the current time. Using "datetime.datetime.utcnow() + datetime.timedelta(days=4)" would work (note the parenthesis) but that would defeat the purpose of setting a time that is always four days after the date_submission value is set – Adventure-Knorrig Aug 16 '21 at 07:01
  • I'm not sure that there's a portable way to specify i"now + 4 days" on the database side, so you might have to do something like `default=lambda: datetime.datetime.utcnow() + datetime.timedelta(days=4)` (untested) – snakecharmerb Aug 16 '21 at 07:13
  • Yeah that's the direction I was leaning. I'll have to check if that would cause a problem with the parenthesis – Adventure-Knorrig Aug 16 '21 at 07:15

1 Answers1

2

Try this code for your date_exipiration column, this would work:

date_expiration = db.Column(db.DateTime, nullable=False, default= (datetime.datetime.today() + datetime.timedelta(days=4)))

Use datetime.datetime.today() instead of datetime.datetime.utcnow. Coz, both are different types, that why you get error.

Fasil K
  • 473
  • 4
  • 17