简体   繁体   中英

How do I find the difference between two datetimes excluding a time gap in the day?

I want to get the datetime from n hours ago before current datetime , excluding a time gap from 16:30 to 8:00.

So if current datetime is datetime(2020, 06, 25, 14, 0) , and I want to get the datetime with a delta of -5 hours, I just get the datetime of datetime(2020, 06, 25, 9, 0) as normal. However, if current time is 10:00, I want the returned datetime to be datetime(2020, 06, 24, 13, 30) . So it excludes the time gap, and returns the datetime as if the time gap doesn't exist at all.

I've tried solving this myself, but it's horrible code, and doesn't really work. I need help finding a better solution.

now = datetime.now()
datetime_new = now - timedelta(hours=N_HOURS)
print(datetime_new)

if datetime_new.hour < 8:
    prev_day = datetime(datetime_new.year,
                        datetime_new.month,
                        datetime_new.day - 1,
                        16, 30)
    this_day = datetime(datetime_new.year,
                        datetime_new.month,
                        datetime_new.day,
                        8, 0)

    diff2prev = datetime_new - prev_day
    diff2next = this_day - datetime_new
    total_diff = diff2prev + diff2next
    datetime_new -= total_diff

elif datetime_new.hour > 16 and datetime_new.minute > 30:
    this_day = datetime(datetime_new.year,
                        datetime_new.month,
                        datetime_new.day,
                        16, 30)
    next_day = datetime(datetime_new.year,
                        datetime_new.month,
                        datetime_new.day + 1,
                        8, 0)

    diff2prev = datetime_new - this_day
    diff2next = next_day - datetime_new
    total_diff = diff2prev + diff2next
    datetime_new -= total_diff

Why don't you try:

datetime_new = now - timedelta(hours=N_HOURS)
if datetime_new.hour < 8 or (datetime_new.hour > 16 and datetime_new.minute > 30):
    datetime_new = datetime_new - timedelta(hours=15,minutes=30)

I think I figured it out. I had to change it that if current time is later than 16:30, it first goes back to 16:30 and then starts applying the delta. It also works only if it's not earlier than 08:00, but this could be fixed with a condition. Here's my solution:

now = datetime.now()
if now > datetime(now.year, now.month, now.day, 16, 30):
    now = datetime(now.year, now.month, now.day, 16, 30)

hours_left = N_HOURS
while hours_left > 0:
    now -= timedelta(hours=1)
    hours_left -= 1

    if now.hour < 8:
        diff_mins = 60 - now.minute
        now = datetime(now.year, now.month, now.day - 1, 16, 30)
        now -= timedelta(minutes=diff_mins)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM