-1

This is my date string myString = "13MAY2022"

Can anyone tell me please how can we change this myString into datetime format in python?

moully
  • 37
  • 2
  • You can visit to this https://stackoverflow.com/questions/466345/converting-string-into-datetime – Kishan Yadav May 12 '22 at 06:58
  • 1
    Dates are binary values, not strings, and have no format. You're asking how to *parse* a string into a date. That's the job of [datetime.strptime](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior) – Panagiotis Kanavos May 12 '22 at 07:03

1 Answers1

0

This should work:

>>> import datetime
>>> myString = "13MAY2022"
>>> dateformat = datetime.datetime.strptime(myString, "%d%b%Y")
>>> dateformat
datetime.datetime(2022, 5, 13, 0, 0)

strptime is a method to convert date strings into date format. It's first argument is our string and the second argument is locale references in the same order and patter our string has.

For example your string has no spaces in between and is in DateMonthYear order. Suppose you string looks like : 13-May-2022, then the second argument would look like: "%d-%b-%Y"

Shivam Pandya
  • 251
  • 3
  • 10
  • it throw error File "", line 3 dateformat = datetime.datetime.strptime(myString, "%d%b%Y') ^ SyntaxError: EOL while scanning string literal – moully May 12 '22 at 07:08
  • Your use of quotation marks is not consistent. You have written: "%d%b%Y' It starts with double quotes but ends with single quote. – Shivam Pandya Jun 01 '22 at 10:06