3

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

Dave
  • 15,639
  • 133
  • 442
  • 830

3 Answers3

9

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(...)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
-1

You should use the correct import:

from datetime import timedelta

new_date = article.created_on + timedelta(0, elapsed_time_in_seconds)
Dos
  • 2,250
  • 1
  • 29
  • 39
-1

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

8oris
  • 320
  • 2
  • 12