How to solve "type object 'datetime.datetime' has no attribute 'timedelta'" when creating a new date?

Question:

I’m using Django and Python 3.7. I’m trying to calculate a new datetime by adding a number of seconds to an existing datetime. From this — What is the standard way to add N seconds to datetime.time in Python?, I thought i could do

new_date = article.created_on + datetime.timedelta(0, elapsed_time_in_seconds)

where “article.created_on” is a datetime and “elapsed_time_in_seconds” is an integer. But the above is resulting in an

type object 'datetime.datetime' has no attribute 'timedelta'

error. What am I missing

Asked By: Dave

||

Answers:

You’ve imported the wrong thing; you’ve done from datetime import datetime so that datetime now refers to the class, not the containing module.

Either do:

import datetime
...article.created_on + datetime.timedelta(...)

or

from datetime import datetime, timedelta
...article.created_on + timedelta(...)
Answered By: Daniel Roseman

Use the correct import:

from datetime import timedelta

new_date = article.created_on + datetime.timedelta(0, elapsed_time_in_seconds)
Answered By: Dos

I got the same issue, i solved it by replacing
from datetime import datetime as my_datetime
with
import datetime as my_datetime

Answered By: 8oris
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.