datetime.date Arguments From Tuple

I always forget this, so maybe writing it down will help. When converting strings to time objects, with time.strptime(str, format), you can't pass the tuple directly to datetime.date because each part of the tuple is a positional argument. So, for example, the following fails:

datetime.date(time.strptime(d, "%a %b %d, %Y")[0:3])

A nice work around is using the star operator.

datetime.date(*time.strptime(d, "%a %b %d, %Y")[0:3])

I'm used to *args and **kwargs when handling arbitrary function arguments and keyword arguments, but the star works nicely to unpack arguments as well. See Unpacking Argument Lists in the Python tutorial for more.

Posted by deryck on September 25, 2006

Post a comment

Comments temporarily closed.