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?
You are really using the wrong tool here; use
datetime.strptime()
instead:and avoid all that splitting and converting-to-integers work. Moreover, this handles incorrect input better, the
%Y
pattern tostrptime()
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 youdatetime.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 applyint
to each split result, then use*
to apply the resulting integers as separate arguments:and this also works with a generator expression:
Demo: