297

I have two objects that represent the same event instance --- one holds the date, the other the time of this event, and I want to create a datetime object.

Since one can't simply add date and time objects (following call fails):

 datetime.date(2011, 01, 01) + datetime.time(10, 23)
1

1 Answer 1

489

It's in the python docs.

import datetime
datetime.datetime.combine(datetime.date(2011, 1, 1), 
                          datetime.time(10, 23))

returns

datetime.datetime(2011, 1, 1, 10, 23)
Sign up to request clarification or add additional context in comments.

6 Comments

This loses the tzinfo though (if the date has one). Is there a way to keep it?
And in Python 3? Can't find combine()
@OlivierPons nothing has changed in Python3: docs.python.org/3/library/…
I'm sorry you're right, combine() can be applied to a datetime value. Thanks a lot
In Python 3.6, you can use the tzinfo argument to preserve timezone: docs.python.org/3/library/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.