Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python create datetime object from list of values

I have a list with values for datetime object:

values = ['2014', '08', '17', '18', '01', '05']

Convert it to int: values = map(int, values)

And now I need to create newdate:

newdate = datetime.datetime(values[0], values[1], values[2], values[3], values[4], values[5])

Is there better way to do this?

like image 207
xijhoy Avatar asked Aug 27 '14 09:08

xijhoy


1 Answers

Use parameter expansion:

newdate = datetime.datetime(*values)

The *expression syntax in a call takes the output of expression as a sequence and applies each element as a separate argument.

This'll work for any sequence with a length between 3 and 8 elements, provided the first 7 are all integers and the 8th, if present, is a datetime.tzinfo subclass.

Combined with mapping to int:

values = ['2014', '08', '17', '18', '01', '05']
newdate = datetime.datetime(*map(int, values))

Demo:

>>> import datetime
>>> values = ['2014', '08', '17', '18', '01', '05']
>>> datetime.datetime(*map(int, values))
datetime.datetime(2014, 8, 17, 18, 1, 5)
like image 116
Martijn Pieters Avatar answered Sep 24 '22 15:09

Martijn Pieters