0

I have a string "Monday, May 18, 2015". I want to convert it into datetime fromat of python keeping the format same. I mean exact replica of the string but the type changed to datetime. How can I do that?

ZdaR
  • 22,343
  • 7
  • 66
  • 87
bazinga
  • 2,120
  • 4
  • 21
  • 35
  • 3
    A [`datetime`](https://docs.python.org/3/library/datetime.html#datetime-objects) does not *have* a format, it can be *formated using a format*. What you ask for makes no sense. –  May 19 '15 at 09:57

3 Answers3

0
from datetime import datetime

date_object = datetime.strptime('MAY 18 2015  1:33PM', '%b %d %Y %I:%M%p')

Link to the Python documentation for strptime :https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

and a link for the strftime format mask : https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime

Yalami
  • 63
  • 1
  • 3
  • 11
0

To convert string to date object:

from datetime import datetime

your_date_object = datetime.strptime("Monday, May 18, 2015", '%A, %b %d, %Y')

To change back date object to string:

your_date_object.strftime('%A, %b %d, %Y')

For more derivative behaviour: https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

no coder
  • 2,290
  • 16
  • 18
-1

Use the classmethod of datetime.strptime(date_string, format). This will return a datetime corresponding to date_string, parsed according to format.

  • 1
    How is your answer different from the existing two answers? It is a bad copy. –  May 19 '15 at 10:10