Krithika Raghavendran
Krithika Raghavendran

Reputation: 457

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?

Upvotes: 3

Views: 5708

Answers (1)

EdChum
EdChum

Reputation: 394469

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

Upvotes: 6

Related Questions