Search code examples
pythondatetimetimedelta

Calculate and substract specific time for a date that is not today


I'm trying to code an auto-shutdown for my pc. I'm fairly new to progamming, to this may be easy to solve.

I have 2 dates

import datetime
startup_date = datetime.datetime.now() #This is the datetime when I start up my pc
shutdown_date = startup_date + datetime.timedelta(days=1) #Tomorrow

So, I want to make that shutdown_date happens at the next day 3 AM. I figured how to obtain tomorrow's date, but I don't know how to make that calculation in order to always have the timer pointing at next day 3 AM. Somedays I startup my pc at 12 pm, other days at 2pm. So I need to automatically calculate the difference between the startup timedate and the desired shutdown time (next day at 3 AM).

I'm sure this is pretty easy to solve, but I can't see it.

Thank you!


Solution

  • You could:

    1. get today's date
    2. add a day to it
    3. replace its hour to 3AM:
    import datetime
    
    startup_date = datetime.datetime.now()
    shutdown_date = startup_date + datetime.timedelta(days=1)
    shutdown_date = shutdown_date.replace(hour=3, minute=0, second=0, microsecond=0)