Python datetime.strptime - Convert month to String to Digit
I have a string that contains a date in this format:
full_date = "May.02.1982"
I want to use datetime.strptime () to display date on all digits like: "1982-05-02"
Here's what I've tried:
full_date1 = datetime.strptime(full_date, "%Y-%m-%d")
When I try to print this I get garbage values like built-in-67732
Where am I going wrong? Doesn't strptime () method support string values?
source to share
Your format string is wrong, it should be like this:
In [65]:
full_date = "May.02.1982"
import datetime as dt
dt.datetime.strptime(full_date, '%b.%d.%Y')
Out[65]:
datetime.datetime(1982, 5, 2, 0, 0)
Then you need to call strftime
on the datetime object to get your desired string format:
In [67]:
dt.datetime.strptime(full_date, '%b.%d.%Y').strftime('%Y-%m-%d')
Out[67]:
'1982-05-02'
strptime
is intended to create a date format from a string, not to format a string into another datetime string.
So, you need to create a datetime object using strptime
and then call strftime
to create a string from the datetime object.
The datetime format strings can be found in the docs , along with an explanation strptime
andstrftime
source to share