How to make it one-liner? Convert list to a bunch of parameters

151 views Asked by At

I have the following code:

from datetime import datetime 

ds = "2020.10.10.12.30.59"

y, M, d, h, m, s = [int(x) for x in ds.split('.')]
dt = datetime(y, M, d, h, m, s)

print(dt)

I would like to make it to one-liner something like this:

dt = datetime([int(x) for x in ds.split('.')])

of course this is not working. But can it be done somehow?

2

There are 2 answers

0
Martijn Pieters On BEST ANSWER

You are really using the wrong tool here; use datetime.strptime() instead:

dt = datetime.strptime(ds, "%Y.%m.%d.%H.%M.%S")

and avoid all that splitting and converting-to-integers work. Moreover, this handles incorrect input better, the %Y pattern to strptime() will not accept a 2-digit year, but the split-and-convert method would accept it, but give you incorrect dates (e.g. 20.10.10.12.30.59 would give you datetime.datetime(20, 10, 10, 12, 30, 59) instead of raising an exception).

If you must use splitting and conversion, then you could use map() to apply int to each split result, then use * to apply the resulting integers as separate arguments:

dt = datetime(*map(int, ds.split(".")))

and this also works with a generator expression:

dt = datetime(*(int(s) for s in ds.split(".")))

Demo:

>>> from datetime import datetime
>>> ds = "2020.10.10.12.30.59"
>>> datetime.strptime(ds, "%Y.%m.%d.%H.%M.%S")
datetime.datetime(2020, 10, 10, 12, 30, 59)
5
Carcigenicate On

From that point, you just need to spread using unpacking:

dt = datetime(*[int(x) for x in ds.split('.')])

Note the *. This "spreads" the data into each argument.