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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.