The fastest way to convert a long list of date

Peter Otten __peter__ at web.de
Sun Feb 8 08:52:27 EST 2009


loredana.pier at gmail.com wrote:

> If I want to convert a single date format I can do:
> 
> import datetime, dateutil.parser
> d = dateutil.parser.parse('2008-09-26)
> print d.strftime('%A %d, %b %y' )
> 
> but if I want convert a long list of time how can do it in the fastest
> way?
> for example:
> from ['2008-09-26’, '2008-09-28’, '2008-09-29’,.............]
> to [’26 sep’,’28 sep’,’29 sep’,................]

For large source lists the following should be quite fast...

months = "jan feb mar apr may jun jul aug sep oct dec".split()
lookup = dict(("%02d-%02d" % (mi+1, d), "%02d-%s" % (d, m)) for mi, m in
enumerate(months) for d in range(1, 32))

source = ["2008-09-26", "2008-09-28", "2008-09-29"]
print [lookup[d[-5:]] for d in source]


... but it is also very brittle. Various compromises are possible, but to
find the best would require that you tell us a bit more about your use
case. In my experience people are a bit too fast to demand "fast".

Peter



More information about the Python-list mailing list