I have lots of dates in a column in a CSV file that I need to convert from dd/mm/yyyy to yyyy-mm-dd format. For example 17/01/2010 should be converted to 2010-01-17.
How can I do this in Perl or Python?
I have lots of dates in a column in a CSV file that I need to convert from dd/mm/yyyy to yyyy-mm-dd format. For example 17/01/2010 should be converted to 2010-01-17.
How can I do this in Perl or Python?
In glorious perl-oneliner form:
But seriously I would do it like this:
Which will work on a pipe, converting and printing one date per line.
Perl:
If you are guaranteed to have well-formed data consisting of nothing else but a singleton date in the DD-MM-YYYY format, then this works:
That works on a
$date
holding "07/04/1776" but fails on "this 17/01/2010 and that 01/17/2010 there". Instead, use:If you prefer a more "grammatical" regex, so that it’s easier to maintain and update, you can instead use this:
Finally, if you have Unicode data, you might want to be a bit more careful.
You can see how each of these four approaches performs when confronted with sample input strings like these:
Now letting
$date
be aforeach
iterator through that array, we get this output:In Perl you can do:
Go with Perl: the
datetime
Python package is just broken. You could just do it with regexes to swap the date parts around, egIf you do need to parse these dates (eg to compute their day of week or other calendar-type operations), look into DateTimeX::Easy (you can install it with
apt-get
under Ubuntu):Perl :
Then you just have to run: