Twinlio
Twinlio

Reputation: 41

AttributeError: module 'datetime' has no attribute 'today' | datetime

Keep getting this error that the package is not being installed. Any Fixes?

from datetime import datetime, date, timedelta

time_change = datetime.timedelta(hours=2)

today_var = datetime.today().date() + time_change
print(today_var)

AttributeError: module 'datetime' has no attribute 'today'

Upvotes: 2

Views: 3437

Answers (2)

user8128167
user8128167

Reputation: 7676

This line import datetime imports the datetime module, but not the datetime class:

import datetime
attributes = dir(datetime)
print('today' in attributes)
False

To access the datetime class, you need to add the line from datetime import datetime:

import datetime
from datetime import datetime
attributes = dir(datetime)
print('today' in attributes)
True

So now you can access datetime.today():

import datetime
from datetime import datetime, date, timedelta

time_change = datetime.timedelta(hours=2)
today_var = datetime.today().date() + time_change
print(today_var)

For details see https://researchdatapod.com/how-to-solve-python-attributeerror-module-datetime-has-no-attribute-today/

Upvotes: 1

Bill
Bill

Reputation: 11658

Try this:

time_change = timedelta(hours=2)

You already imported datetime.timedelta as timedelta so you can use that.

But you imported datetime.datetime as datetime so that is why it is saying 'datetime.datetime' has no attribute 'timedelta'.

Upvotes: 3

Related Questions