Skip to content
Advertisement

AttributeError: module ‘datetime’ has no attribute ‘strftime’

I’ve been trying to get today’s year, month, and day using datetime. So, I imported the datetime module using import datetime. However, I also needed the timedelta command, so I used from datetime import timedelta. I’m also using strftime, which I believe is gotten from from datetime import datetime. However, I can’t run all of these at once.

So, how can I use the datetime module, with strftime, and timedelta? Any help is appreciated!

Advertisement

Answer

working with datetime gets very confusing once you consider that datetime is both the package name and a module name inside datetime.

the datetime package has a lot of different modules, namely:

datetime module handles datetime objects.

date module handles date objects.

time module handles time objects.

timedelta module handles timedelta objects.

In your case, when you said import datetime, what you’re really referring to is the datetime package NOT the datetime module.

strftime is a method of datetime objects (i.e. under the datetime module)

therefore, you have 2 ways to go about this.

If you went with import datetime, then you have to specify the package, the module THEN the method, like so:

import datetime

today = datetime.datetime.now()
today.strftime('%Y-%m-%d')

or the better, more human readable way is to just import the datetime module under the datetime package by doing a from *package* import *module*. Applied to the datetime package, that means: from datetime import datetime like so:

from datetime import datetime

today = datetime.now()
today.strftime('%Y-%m-%d')

OR, my preferred method, is to give the module an alias (or basically a “nickname”), so it doesn’t get confusing (LOL):

from datetime import datetime as dt
from datetime import timedelta as td

today = dt.now() # get date and time today
delta = td(days=3) #initialize delta
date_you_actually_want = today + delta # add the delta days
date_you_actually_want.strftime('%Y-%m-%d') # format it

hope that clears it up for you.

Advertisement