Kingbuttmunch Kingbuttmunch - 7 months ago 11
Python Question

How to deduct the current time from a set time

So I am trying to create a 'planner' or diary. I am trying to create the code so it advises you how much time you have left in the day before you go to bed or before you have to do an activity you have planned.

late = timedelta(hours=23)
current_time = now.hour,now.minute
time_left = (late - current_time).minutes
print 'So if the time is %s:%s, That means you have %s minutes left' % (now.hour,now.minute,time_left)


From looking at other threads this was my approach but I have tried several other methods like

late = datetime(datetime.day,datetime.month,datetime.year,23,00)


Again saw this on other threads. I have tried so many methods now I have begun to confuse myself with how to solve it.

Thanks again for any help in advance

EDIT:
when using

late = datetime(datetime.day,datetime,month,datetime.year,23,00)


I got the Valuerror 'day is out of range month'

and with the current code

late = timedelta(23,00)


I got a typeerror 'unsupported operand type(s) for -: 'datetime.timedelta' and 'tuple' In this example.

I just want the code to output the time difference between 11:00pm (or 23:00) and the current time in minutes. Sorry for not being clearer

ANSWERED EDIT:
Thank you to the comments and the answer the problem I was making the code to complicated and not using datetime() correctly,

y = today.year
m = today.month
d = today.day

late = datetime(y,m,d,23,0,0)


I had the year month and day the wrong way round and had the format for the time wrong.

Thanks for the help guys.

Answer

The following would demonstrate how to do what you want to achieve

from datetime import datetime


today = datetime.today()
y = today.year
m = today.month
d = today.day

late = datetime(y,m,d,23,0,0)

now = datetime.now()

timeDiff = late - now
print 'So if the time is %s:%s, That means you have %s minutes left' % (now.hour,now.minute,timeDiff.seconds/60) 

The __sub__ method has been implemented for datetime but obviously to use the operator both operands have to be of type datetime.

>>> datetime.now().__class__
<type 'datetime.datetime'>

When you subtract one datetime object from another you get an object of type timedelta.

>>> (datetime(2016,04,19)-datetime(2016,04,18)).__class__
>>> <type 'datetime.timedelta'>

datetime represents a timestamp while timedelta represents time difference.

It is possible to subtract a timedelta object from a datetime object but not vice versa and that is self-explanatory.

>>> datetime(2016,10,1)-timedelta(1)
datetime.datetime(2016, 9, 30, 0, 0)