Python Forum
Subtract Minutes from Datetime.Time - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Subtract Minutes from Datetime.Time (/thread-3262.html)



Subtract Minutes from Datetime.Time - tkj80 - May-09-2017

Hi, I have a datetime.time object such as:

update_Dt.time()
Output:
datetime.time(21, 30)
How do I subtract 5 minutes from the update_Dt.time() object?

I tried:

update_Dt.time() - timedelta(minutes=15)
I got the error message saying that:

Error:
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.timedelta'
Thank you


RE: Subtract Minutes from Datetime.Time - zivoni - May-11-2017

timedelta works with datetime.datetime, so you need to add it directly to update_Dt and after that use .time() to get time part only (supposing that your update_Dt is a datetime):
(update_Dt - timedelta(minutes=15)).time()
If you have only datetime.time object to start with, you need to convert it to a datetime.datetime, add timedelta and convert back:
In [1]: import datetime

In [2]: my_time = datetime.time(21, 30)

In [3]: (datetime.datetime.combine(datetime.date(1, 1, 1), my_time) - datetime.timedelta(minutes=15)).time()
Out[3]: datetime.time(21, 15)



RE: Subtract Minutes from Datetime.Time - klllmmm - May-11-2017

import datetime as dt
update_Dt=dt.datetime.now()

update_Dt.time()
Out[9]: datetime.time(15, 24, 2, 737247)

newupdate_Dt = update_Dt - dt.timedelta(minutes=15)

newupdate_Dt.time()
Out[11]: datetime.time(15, 9, 2, 737247)