Convert string into datetime.time object

PythonTimePython Datetime

Python Problem Overview


Given the string in this format "HH:MM", for example "03:55", that represents 3 hours and 55 minutes.

I want to convert it to datetime.time object for easier manipulation. What would be the easiest way to do that?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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

Solution 3 - Python

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZedView Question on Stackoverflow
Solution 1 - PythonMartijn PietersView Answer on Stackoverflow
Solution 2 - PythonAndreas JungView Answer on Stackoverflow
Solution 3 - PythonGil Ben-HerutView Answer on Stackoverflow