How to modify datetime.datetime.hour in Python?

PythonDatetime

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

Try this:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMars LeeView Question on Stackoverflow
Solution 1 - PythonChrisView Answer on Stackoverflow
Solution 2 - PythonSelcukView Answer on Stackoverflow