Search code examples
pythondatetimetimedelta

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.


Solution

  • 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)