Skip to main content

Convert time string to datetime.time object

I'm still finding my way around the rather vast Python standard library. And today, I discovered a quick way to convert a pure time string (of format HH:MM[:SS]) into a standard datetime.time object.

datetime.strptime('08:00', '%H:%M').time()
That's it! A single, rather short line of code does the job.

The trick here is that the classmethod datetime.strptime() creates a datetime object with default values for the missing parameters. So the above code creates a datetime object with date set to 1900/1/1 and time set to 8:00AM, with seconds and microseconds set to 0. And from this datetime object we can extract the time component by calling the time() method. Cool!