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.

Vikas Periyadath
  • 3,088
  • 1
  • 21
  • 33
Manoj
  • 1
  • 1
  • 4
    Does this answer your question? [Convert string into Date type on Python](https://stackoverflow.com/questions/9504356/convert-string-into-date-type-on-python) – pk786 Feb 28 '20 at 06:48

2 Answers2

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'>
Vikas Periyadath
  • 3,088
  • 1
  • 21
  • 33
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?

Masklinn
  • 34,759
  • 3
  • 38
  • 57