tags:

views:

54

answers:

2

Hi if I do the following I can convert from a time_struct object to a datetime object:

mydate = datetime.datetime(*time.localtime()[:6])

How does this code work? What do the * and the [:6] mean?

+3  A: 

*time.localtime() means, that the tuple returned from localtime is unpacked (turned into arguments passed to datetime). [:6] means that only a slice of the tuple is used, this operator returns new tuple of first six elements.

This code takes localtime from the time module in the form of a tuple and passes it into nice datetime object constructor. It's good to work on datetime objects, they are much nicer then localtime tuples. localtime returns a tuple with values representing local time.

gruszczy
Reference 1: The "*" operator: http://docs.python.org/reference/compound_stmts.html#function-definitions
S.Lott
Reference 2: The [:] slicing operation: http://docs.python.org/reference/expressions.html#slicings
S.Lott
+4  A: 

* is argument unpacking, [:6] is slicing. That is whatever is returned from time.localtime() (i.e., time.struct_time) is sliced and first 6 elements are unpacked and 6 arguments passed to datetime.datetime.

There are plenty of question on SO re all of these topics.

SilentGhost