Andrea
Andrea

Reputation: 748

Python DateTime minus TimeDelta vs TimeDelta minus DateTime

Say I have the datetime now:

import datetime
now = datetime.datetime(2019, 10, 3, 1, 57, 3, 939862)

print(now)
2019-10-03 01:57:03.939862

and I have a timedelta for the start of business day (07:00:00).

start_biz_dt = datetime.timedelta(hours = 7)

I want to do a calculation that gives me the time from now to start of business day. ie, I want:

6:03:56.060138

But I obviously cannot do:

start_biz_dt - now

I could give start_biz_dt the same date as now, but I have many datetimes in a column of various dates, so this might not be the best way. Any help is appreciated.

Upvotes: 0

Views: 102

Answers (1)

Olvin Roght
Olvin Roght

Reputation: 7812

To find closest 07:00:00, so you can use next code:

from datetime import datetime, timedelta

start_of_business_day = datetime.now().replace(hour=7, minute=0, second=0)
if start_of_business_day < datetime.now():
    start_of_business_day += timedelta(days=1)

To calculate how much left just substitute current datetime from start_of_business_day:

sleep_time = start_of_business_day - datetime.now()

Upvotes: 1

Related Questions