Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python datetime.strptime - Converting month in String format to Digit

I have a string that contains the date in this format: full_date = "May.02.1982"

I want to use datetime.strptime() to display the date in all digits like: "1982-05-02"

Here's what I 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? Does the strptime() method not accept string values?

like image 235
Krithika Raghavendran Avatar asked Mar 22 '26 09:03

Krithika Raghavendran


1 Answers

Your format string is wrong, it should be 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)

You then need to call strftime on a datetime object to get the string format you desire:

In [67]:

dt.datetime.strptime(full_date, '%b.%d.%Y').strftime('%Y-%m-%d')
Out[67]:
'1982-05-02'

strptime is for creating a datetime format from a string, not to reformat a string to another datetime string.

So you need to create a datetime object using strptime, then call strftime to create a string from the datetime object.

The datetime format strings can be found in the docs as well as an explanation of strptime and strftime

like image 155
EdChum Avatar answered Mar 24 '26 00:03

EdChum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!