The Python Oracle

Python DateUtil Converting string to a date and time

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Underwater World

--

Chapters
00:00 Python Dateutil Converting String To A Date And Time
00:52 Answer 1 Score 4
01:05 Accepted Answer Score 8
01:30 Thank you

--

Full question
https://stackoverflow.com/questions/7834...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #pyodbc #pythondateutil

#avk47



ACCEPTED ANSWER

Score 8


The problem you're having is that any arguments you pass to parser.parse only affect how the string is parsed, not how the subsequent object is printed.

parser.parse returns a datetime object - when you print it it will just use datetime's default __str__ method. If you replace your last line with

print dt.strftime("%d-%m-%Y %H:%M:%S")

it will work as you expect.




ANSWER 2

Score 4


The standard lib (built-in) datetime lib can do this easily.

from datetime import datetime

my_date_string = "2001/9/1 12:00:03"
d = datetime.strptime(my_date_string, "%Y/%m/%d %H:%M:%S")
print d.strftime("%d-%m-%Y %H:%M:%S")