Take the 2-minute tour ×

Using a Python script, I need to read a CVS file where dates are formated as DD/MM/YYYY, and convert them to YYYY-MM-DD before saving this into a SQLite database.

This almost works, but fails because I don't provide time:

from datetime import datetime

lastconnection = datetime.strptime("21/12/2008", "%Y-%m-%d")

#ValueError: time data did not match format:  data=21/12/2008  fmt=%Y-%m-%d
print lastconnection

I assume there's a method in the datetime object to perform this conversion very easily, but I can't find an example of how to do it. Thank you.

share|improve this question
add comment

3 Answers

Your example code is wrong. This works:

datetime.datetime.strptime("21/12/2008", "%d/%m/%Y").strftime("%Y-%m-%d")

The call to strptime() parses the first argument according to the format specified in the second, so those two need to match. Then you can call strftime() to format the result into the desired final format.

share|improve this answer
add comment

you first would need to convert string into datetime tuple, and then convert that datetime tuple to string, it would go like this:

lastconnection = datetime.strptime("21/12/2008", "%d/%m/%Y").strftime('%Y-%m-%d')
share|improve this answer
Saying "tuple" seems a bit confusing; as of Python 2.2, strptime() returns "a struct_time", which is an object with a "named tuple" interface. –  supervacuo Jul 6 '12 at 16:54
add comment

Does anyone else else think it's a waste to convert these strings to date/time objects for what is, in the end, a simple text transformation? If you're certain the incoming dates will be valid, you can just use:

>>> ddmmyyyy = "21/12/2008"
>>> yyyymmdd = ddmmyyyy[6:] + "-" + ddmmyyyy[3:5] + "-" + ddmmyyyy[:2]
>>> yyyymmdd

This will almost certainly be faster than the conversion to and from a date.

share|improve this answer
If you're worried about the speed of converting to date the you clearly have nothing else left to worry about it. The code posted by unwind is so much clearer and maintainable than yours. That should be your primary concern here, not speed. –  Andrew Wilkinson Feb 2 '09 at 10:55
I miss the ability to vote up this comment. –  Sebastian Rittau Feb 2 '09 at 16:56
add comment

Your Answer

