0

I've got a list of dates (datetimes):

>>> print str(range)
[datetime.datetime(2011, 12, 15, 0, 0), datetime.datetime(2011, 12, 16, 0, 0), datetime.datetime(2011, 12, 17, 0, 0)]

and I'd like to format them as "%d/%m/%Y" and comma separate them, ie:

15/12/2011, 16/12/2011, 17/12/2011

At the moment I'm using map to run strftime on each of the dates like so:

>>> string = ", ".join(map(lambda x: x.strftime("%d/%m/%Y"), range))
>>> print string

which outputs:

15/12/2011, 16/12/2011, 17/12/2011

Ta dah!

It's not the easiest to read, but it works. Is it efficient? Is it pythonic? (does that matter?)

2 Answers 2

2

map() is considered deprecated (although there are those that will argue otherwise).

", ".join(x.strftime("%d/%m/%Y") for x in daterange)
Sign up to request clarification or add additional context in comments.

6 Comments

Why "map() is considered deprecated"? Could you provide a source?
I'm going to argue otherwise on that point, simply because map() still exists in Python 3.2 with no deprecation notice. However, I agree that the "map-with-lambda" pattern is better implemented with a comprehension or generator.
@Greg: But it's no longer the same map().
That's a pretty fine point, since either one would work equally well in the OP's code.
That's not a list comprehension, it's a generator expression. It trades the initial cost of generating the list for a per-access cost of generating each element.
|
0

why not use list expression?

",".join([ date.strftime("%d/%m/%Y") for date in range])

yes, map is deprecated, this is in the official documentation, because list expression is better optimized.

2 Comments

It doesn't say deprecated on the page I'm looking at here. Could you show me where you see deprecated?
OK, i think "deprecated" maybe a little bit too much, sorry for that, "not encouraged" is better for the performance issue. I guess it comes out from link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.