jpatokal jpatokal - 1 year ago 63
Python Question

Combining a parsed time with today's date in Python

This should be easy, but as ever Python's wildly overcomplicated datetime mess is making simple things complicated...

So I've got a time string in HH:MM format (eg. '09:30'), which I'd like to turn into a datetime with today's date. Unfortunately the default date is Jan 1 1900:

>>> datetime.datetime.strptime(time_str, "%H:%M")
datetime.datetime(1900, 1, 1, 9, 50)

datetime.combine looks like it's meant exactly for this, but I'll be darned if I can figure out how to get the time parsed so it'll accept it:

now =
>>> datetime.datetime.combine(now, time.strptime('09:30', '%H:%M'))
TypeError: combine() argument 2 must be datetime.time, not time.struct_time

>>> datetime.datetime.combine(now, datetime.datetime.strptime('09:30', '%H:%M'))
TypeError: combine() argument 2 must be datetime.time, not datetime.datetime

>>> datetime.datetime.combine(now, datetime.time.strptime('09:30', '%H:%M'))
AttributeError: type object 'datetime.time' has no attribute 'strptime'

This monstrosity works...

>>> datetime.datetime.combine(now,
datetime.time(*(time.strptime('09:30', '%H:%M')[3:6])))
datetime.datetime(2014, 9, 23, 9, 30)

...but there must be a better way to do that...!?

Answer Source

The function signature says:

datetime.combine(date, time)

so pass a object as the first argument, and a datetime.time object as the second argument:

>>> import datetime as dt
>>> today =
>>> time = dt.datetime.strptime('09:30', '%H:%M').time()
>>> dt.datetime.combine(today, time)
datetime.datetime(2014, 9, 23, 9, 30)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download