8

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?

2
  • do you only have 6 elements in your list? Commented Aug 27, 2014 at 10:01
  • @PadraicCunningham yep Commented Aug 27, 2014 at 10:03

1 Answer 1

21

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.