user3921265
user3921265

Reputation:

Combine datetime.date object with time string in a datetime.datetime object

Say you have a datetime.date object such as that returned by datetime.date.today().

Then later on you also get a string representing the time that complements the date object.

What is a pythonic way of combining these two in a datetime.datetime object? More specifically, can I avoid converting the date object to a string?

This is how I get it done for now:

def combine_date_obj_and_time_str(date_obj, time_str):
    # time_str has this form: 03:40:01 PM
    return datetime.datetime.strptime(date_obj.strftime("%Y-%m-%d") + ' ' + time_str, "%Y-%m-%d %I:%M:%S %p")

EDIT:

I looked into datetime.datetime.combine as the first answer describes, but I am a bit at loss with getting the time string into a time object:

>>> datetime.datetime.combine(datetime.date.today(), time.strptime("03:40:01 PM", "%I:%M:%S %p"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: combine() argument 2 must be datetime.time, not time.struct_time
>>> datetime.datetime.combine(datetime.date.today(), datetime.time.strptime("03:40:01 PM", "%I:%M:%S %p"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'datetime.time' has no attribute 'strptime'

Upvotes: 1

Views: 2637

Answers (1)

abarnert
abarnert

Reputation: 365607

If you just read the docs for datetime, or look at the help(datetime) in the interactive interpreter, you'll see the combine method:

classmethod datetime.combine(date, time)

Return a new datetime object whose date components are equal to the given date object’s, and whose time components and tzinfo attributes are equal to the given time object’s. For any datetime object d, d == datetime.combine(d.date(), d.timetz()). If date is a datetime object, its time components and tzinfo attributes are ignored.

So, you don't have to write the method yourself; it's already there in the module.

Of course you need to parse that time_str into a time object, but you clearly already know how to do that.


But if you did want to write it yourself, formatting the date and time as strings just to parse them back out would be silly. Why not just access the attributes directly?

return datetime(d.year, d.month, d.day, t.hour, t.minute. t.second, t.tzinfo)

Upvotes: 5

Related Questions