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?
Asked
Active
Viewed 519 times
0
-
3A [`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 Answers
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
-
Now we have a `datetime.datetime` instance. Fince. The second part of an answer would be to format this instance as a string. – May 19 '15 at 10:00
-
1
-
-
this is a direct copy paste of this answer http://stackoverflow.com/a/466376/2141635 – Padraic Cunningham May 19 '15 at 10:45
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.