Abid Rasheed
Abid Rasheed

Reputation: 81

Subtracting a string converted into a datetime object

I have a piece of code, which takes inputs in 24 hour time such as 23:59, and prints how much time is left, so if it was 11:59 in the morning, it would return 12 hours.

I have been able to do this so far, but I cannot tell what is going wrong with this code right now:

from datetime import datetime

def timeuntil(t): 
    time = t
    future = datetime.strptime(time, '%H:%M').replace(day = datetime.now().day, year = datetime.now().year, month = datetime.now().month)
    timeleft = (future - datetime.now())
    return timeleft

For your reference, print(timeuntil(22:00)) returned 15:55:01.996377 when I ran it at 8:43 PM.

Thanks for your help.

Upvotes: 1

Views: 88

Answers (2)

PacketLoss
PacketLoss

Reputation: 5746

The issue does not seem reproducible on my machine, even when defining the datetime objects to the time you specified. However It could be to do with replace() on your datetime.

There is really no need for this, and I think you would be best to create a datetime object correctly. Below addresses the problem and works as you have intended.

def timeuntil(begin):
    hour, minute = map(int, begin.split(':'))
    now = datetime.now()
    future = datetime(now.year, now.month, now.day, hour, minute)
    return (future - now)

print(timeuntil("23:59"))
#7:35:06.022166

If you want to specify a different timezone to run this in, we can define our datetime.now() with a timezone, however we will need to strip this off to calculate future - now.

def timeuntil(begin):
    hour, minute = map(int, begin.split(':'))
    now = datetime.now(timezone('US/Pacific')).replace(tzinfo=None)
    future = datetime(now.year, now.month, now.day, hour, minute)
    return (future - now)

Upvotes: 2

Bobby Ocean
Bobby Ocean

Reputation: 3294

I believe you want the number of seconds until you reach the next day. I find this easier to follow with the time module and direct calculations.

import time
secs_in_day          = 60*60*24
secs_time_left_local = secs_in_day - (time.time() - time.altzone) % secs_in_day
hours                = int(secs_time_left_local // 3600)
minutes              = int((secs_time_left_local % 3600) // 60)
seconds              = int((secs_time_left_local % 3600) % 60)
print(f'{hours:02}:{minutes:02}:{seconds:02}')

    

Upvotes: 0

Related Questions