将字符串转换为 datetime.time 对象

给定这种格式的 string,例如 "03:55",它表示 3小时55分钟

我想把它转换成 datetime.time对象,这样操作起来更容易。最简单的方法是什么?

101950 次浏览

Use datetime.datetime.strptime() and call .time() on the result:

>>> datetime.datetime.strptime('03:55', '%H:%M').time()
datetime.time(3, 55)

The first argument to .strptime() is the string to parse, the second is the expected format.

>>> datetime.time(*map(int, '03:55'.split(':')))
datetime.time(3, 55)

It is perhaps less clear to future readers, but the *map method is more than 10 times faster. See below and make an informed decision in your code. If calling this check many times and speed matters, go with the generator ("map").

In [31]: timeit(datetime.strptime('15:00', '%H:%M').time())
7.76 µs ± 111 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)




In [28]: timeit(dtime(*map(int, SHUTDOWN_AT.split(':'))))
696 ns ± 11.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Simply load if as iso:

>>> from datetime import time
>>> time.fromisoformat("03:55")
datetime.time(3, 55)