0

I have a string object

value="2020-02-28" 

and want output as a date object in python. Used

datetime_value= datetime.strptime((str(value), "%b%d, %Y")) 

But it does not work.

1

2 Answers 2

0

Make these minor changes :

from _datetime import datetime

value="2020-02-28"
datetime_value= datetime.strptime(value, "%Y-%m-%d")

print(datetime_value, type(datetime_value))
# 2020-02-28 00:00:00 <class 'datetime.datetime'>
Sign up to request clarification or add additional context in comments.

Comments

0

First, "it does not work" is really not helpful in any way, shape or form. When you request help, providing the actual feedback you get (e.g. error message, traceback, ...) is significantly more actionable than providing... nothing.

Second, the format string passed to strptime (second parameter) is supposed to match the actual date, that means the placeholders should parse the fields you're trying to match, and the not-placeholders should match the not-fields.

Here your date is {year}-{month}-{day-of-month}, but the format string %b%d, %Y stands for {Month as locale’s abbreviated name}{Day of the month}, {Year}. None of the separators, fields or order match.

What you want is %Y-%m-%d.

Third, value is a string, why are you converting it to a string again?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.