views:

4737

answers:

3

Hello

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.

+4  A: 

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')
SilentGhost
+11  A: 

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.

unwind
A: 

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
'2008-12-21'

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

paxdiablo
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
I miss the ability to vote up this comment.
Sebastian Rittau