Python creates a datetime object from a list of values

I have a list with values ​​for a 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 a better way to do this?

+6
source share
1 answer

Use parameter extension:

 newdate = datetime.datetime(*values) 

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

This will work for any sequence with a length of 3 to 8 elements, provided that the first 7 are integers and the eighth, if present, is a subclass of datetime.tzinfo .

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) 
+8
source

Source: https://habr.com/ru/post/974415/


All Articles