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
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(...)
Use the correct import:
from datetime import timedelta
new_date = article.created_on + datetime.timedelta(0, elapsed_time_in_seconds)
I got the same issue, i solved it by replacing
from datetime import datetime as my_datetime
with
import datetime as my_datetime
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
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(...)
Use the correct import:
from datetime import timedelta
new_date = article.created_on + datetime.timedelta(0, elapsed_time_in_seconds)
I got the same issue, i solved it by replacing
from datetime import datetime as my_datetime
with
import datetime as my_datetime