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

Time:10-02

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!

CodePudding user response:

You can start with your shutdown_date but then only use the date components, and hardcode the time to 03:00. Then you can subtract that new datetime from your startup_date

>>> import datetime
>>> startup_date = datetime.datetime.now()
>>> shutdown_date = startup_date   datetime.timedelta(days=1)
>>> tomorrow_morning = datetime.datetime(shutdown_date.year, shutdown_date.month, shutdown_date.day, hour=3)
>>> tomorrow_morning - startup_date
datetime.timedelta(seconds=48730, microseconds=54057)

CodePudding user response:

Combine it with a 3 am time:

shutdown_date = datetime.datetime.combine(shutdown_date, datetime.time(3, 0))

CodePudding user response:

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)

  • Related