Search code examples
pythondatetimepython-datetime

write specific hour in a python datetime object


I need to pause a program until 08:00 of the following day, independently on the time the code is run. In other words if it is run at 08:00 today it will pause for 24h, but it was run at 20:00 it would be resumed at 08:00 of the following date.

Here is what I came up with:

from datetime import datetime, timedelta
nowDateTimeObj = datetime.now()
tomorrow = nowDateTimeObj + timedelta(days=1)
tomorrow.hour = 8

Adding the 1 day time delta to the nowDateTimeObj datetime object works well to change the day to tomorrow but generates a time that's 24h relative to now. I want to take this "tomorrow" datetime object and set the hour part at 08:00

but I get the following error:

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

Solution

  • There are various ways to do this, I offer the example below just because it appears more readable to me.

    from datetime import datetime, date
    
    today = date.today()
    tomorrow = datetime(today.year, today.month, today.day+1)
    tomorrow_8am = tomorrow.replace(hour=8)
    
    print(today_date, tomorrow_8am)