How to modify datetime.datetime.hour in Python?

I want to calculate the seconds between now and tomorrow 12:00. So I need to get tomorrow 12:00 datetime object.

This is pseudo code:

today_time = datetime.datetime.now()
tomorrow = today_time + datetime.timedelta(days = 1)
tomorrow.hour = 12
result = (tomorrow-today_time).total_seconds()

But it will raise this error:

AttributeError: attribute 'hour' of 'datetime.datetime' objects is not writable

How can I modify the hour or how can I get a tomorrow 12:00 datetime object?


Use the replace method to generate a new datetime object based on your existing one:

tomorrow = tomorrow.replace(hour=12)

Return a datetime with the same attributes, except for those attributes given new values by whichever keyword arguments are specified. Note that tzinfo=None can be specified to create a naive datetime from an aware datetime with no conversion of date and time data.


Try this:

tomorrow = datetime.datetime(tomorrow.year, tomorrow.month, tomorrow.day, 12, 0, 0)