I have a string like this: Monday April 27 2020, 5:14pm
And I want to convert it to date time in python to become: 24-Apr-2020 5:14pm
Would python be able to do that?
Asked
Active
Viewed 566 times
-3

Timbus Calin
- 13,809
- 5
- 41
- 59

user125104
- 29
- 1
- 6
-
Yes, the `datetime.strptime` class method can parse a string to a datetime, and the `datetime.strftime` instance method can serialise it back to a string. Both require a *format string* which [lets you specify the format of each field](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior). – Masklinn Sep 18 '20 at 12:06
-
2Does this answer your question? [Parse date string and change format](https://stackoverflow.com/questions/2265357/parse-date-string-and-change-format) – atru Sep 18 '20 at 12:08
-
1Does this answer your question? [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime) – svorcan Sep 18 '20 at 12:16
1 Answers
0
from datetime import datetime
str_time = "Monday April 27 2020, 5:14pm"
formatted_time = datetime.strptime(a,"%A %B %d %Y, %I:%M%p")
new_str_representation = formatted_time.strftime("%d-%a-%Y %I:%M%p")
Converting string into datetime
https://docs.python.org/3/library/datetime.html
You can find more informations here.

SWater
- 384
- 1
- 13
-
1While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/27193139) – Ankh Sep 18 '20 at 12:33
-
-
Found a library called dateutil that can do the work. Nice. https://stackoverflow.com/a/16115575/9008640 – user125104 Sep 21 '20 at 10:12