Python create datetime object from list of values

10,227

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)
Share:
10,227
xijhoy
Author by

xijhoy

Updated on June 24, 2022

Comments

  • xijhoy
    xijhoy almost 2 years

    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?