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?
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?
*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.
* 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.