The Python Oracle

Python DateUtil Converting string to a date and time

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC L Beethoven - Piano Sonata No 8 in C

--

Chapters
00:00 Question
01:02 Accepted answer (Score 8)
01:33 Answer 2 (Score 4)
01:50 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")