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!
strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification.
Conclusion # The error "AttributeError module 'datetime' has no attribute 'strptime'" occurs when we try to call the strptime method directly on the datetime module. To solve the error, use the following import import datetime and call the strptime method as datetime. datetime.
To convert datetime to string in Python, use the strftime() function. The strftime() method is a built-in method that returns the string representing date and time using date, time, or datetime object.
Use the datetime. date() Function to Convert Datetime to Date in Python. The datetime() constructor can be utilized to generate a date. The datetime() constructor has three parameters: day, month, and year.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With