102

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?

Shapi
  • 5,493
  • 4
  • 28
  • 39
Zed
  • 5,683
  • 11
  • 49
  • 81

4 Answers4

158

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I have an issue where `strptime` assumes a date when using this method. – user4933 Feb 09 '22 at 08:42
  • @user4933: `strptime()` doesn't assume anything. It doesn't guess, it doesn't have heuristics. It can only parse strings that match the exact format you give it. If you have unexpected output you need to fix your use of the method call. – Martijn Pieters Feb 09 '22 at 16:22
20
>>> datetime.time(*map(int, '03:55'.split(':')))
datetime.time(3, 55)
2

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)
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
GBH
  • 21
  • 3
0

Simply load if as iso:

>>> from datetime import time
>>> time.fromisoformat("03:55")
datetime.time(3, 55)
egvo
  • 1,493
  • 18
  • 26