1

If I have a python time object

import datetime
my_time = datetime.time(2,30,00)

What is the best way of subtracting ten minutes from "my_time"? Please note if time is 00:05:00 for example, expected result of this subtraction is 23:55:00.

I found a way to do it, but it feels like there's probably a better way. Also, I will prob have issues with timezone, using this way. Here it is:

import datetime 
my_time = datetime.time(2,30,00)
temp_date = datetime.datetime.combine(datetime.datetime.today(), my_time)
temp_date = temp_date - datetime.timedelta(minutes=10)
my_time = temp_date.time()

So essentially I first convert time back to datetime, do the operation I want, and then convert it back to time.

Dan C
  • 63
  • 5
  • Does this answer your question? [Subtract hours and minutes from time](https://stackoverflow.com/questions/46402022/subtract-hours-and-minutes-from-time) – Anoushiravan R Aug 14 '22 at 14:51
  • 1
    no, this question is specific about the python time object. I did find a way to do it, but it feels like there's a better way, hence I am asking ( will add the way I found to the question) – Dan C Aug 14 '22 at 14:56

1 Answers1

0

One way is to make a timedelta object, which supports subtraction.

from datetime import timedelta

time_1 = timedelta(hours=2, minutes=30, seconds=00)
time_2 = timedelta(hours=00, minutes=5, seconds=00)
delta = timedelta(minutes=10)

print(time_1 - delta)
print(time_2 - delta)

# Out
# 2:20:00
# -1 day, 23:55:00
Ray
  • 463
  • 4
  • 8
  • 1
    feels better than converting to datetime. So, if you start with a time object, first you do timedelta(hours=my_time.hour, minutes=my_time.minutes, seconds=my_time.seconds), I guess. But then, because I need time again, I have to use https://stackoverflow.com/questions/764184/python-how-do-i-get-time-from-a-datetime-timedelta-object – Dan C Aug 14 '22 at 15:33