How to initialize a datetime.time object from a string?

Question:

Is there a method like datetime.datetime.strptime(), that accepts a string like '16:00' and returns a datetime.time(16,0) object (i.e., an object that holds only time, not date)?

Edit:
I could use datetime.datetime.strptime(), but it would return a datetime.datetime, and I want only time, not a date.

Asked By: Yariv

||

Answers:

import time
time.strptime("16:00", "%H:%M")
Answered By: reptilicus
import datetime
import time
def datetimestrptime(time_string,time_fmt):
     t = time.strptime(time_string,time_fmt)
     return datetime.time(hour=t.tm_hour,minute=t.tm_min,second=t.tm_sec)
print datetimestrptime("16:00","%H:%M")
16:00:00
Answered By: Joran Beasley

The alternative way is using datetime.datetime.strptime() and then extracting time from it.

import datetime

def time_from_str(time_string, format):
     date_time = datetime.datetime.strptime(time_string, format)  # datetime.datetime(1900, 1, 1, 16)
     return date_time.time()
     
time_from_str("16:00","%H:%M")
# 16:00:00

Docs:
For the datetime.strptime() class method, the default value is 1900-01-01T00:00:00.000: any components not specified in the format string will be pulled from the default value.

Answered By: dsaperov
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.