Search code examples
pythondatetimetimestrptime

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


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.


Solution

  • 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