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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With