Python DateUtil Converting string to a date and time

user595985 picture user595985 · Oct 20, 2011 · Viewed 10.9k times · Source

I'm trying to convert a parameter of type string to a date time. I'm using the dateUtil library

  from dateutil import parser
myDate_string="2001/9/1 12:00:03"
dt = parser.parse(myDate_string,dayfirst=True)
print dt

every time i run this i get

2001-09-01 12:00:03

regardless of whether i have dayfirst set as true or Year first set as false. Ideally I just want to have a date in the format DD-MM-YYYY HH:MM:SS. I don't want anything fancy. I am willing to use the datetime library but this doesn't seem to work at all for me. Can anyone give simple expamples of how to convert strings to date time with an explicit format, I'm a noob, so the most basic examples are all i require. I'm using Python 2.7

Answer

Ian R.B. picture Ian R.B. · Oct 20, 2011

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.