tags:

views:

218

answers:

2

This is ugly. How would you do it?

import datetime

t= (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(t[0], t[1], t[2], t[3], t[4], t[5], t[6])

Thanks in advance.

+14  A: 

Generally you can use the func(*tuple) syntax. You can even pass a part of the tuple, which seems like what you're trying to do here:

t = (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(*t[0:7])

This is called unpacking a tuple, and can be used for lists too. Here's another example (from the Python tutorial):

>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]
Eli Bendersky
It works for arbitrary iterables.
Mike Graham
@Mike: nice, thanks
Eli Bendersky
+5  A: 

http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists

 dt = datetime.datetime(*t[:7])
Charles Beattie
Should be dt = datetime.datetime(*t[:7]) according to OPs example.
muhuk
Yes your right.
Charles Beattie