Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Add minutes or seconds to a time only object

I need to add a given number of minutes or seconds to a Time object that comes without the date portion.

For Ex:

Time: 13:00:00 + 10 minutes (Should return 13:10:00)

Time: 21:50:00 + 1800 seconds (Should return 22:20:00)

My code:

from datetime import timedelta

d = timedelta(minutes=30)
calendar_entry + d  #calendar_entry is a time object HH:MM:SS

Error:

During handling of the above exception (unsupported operand type(s) 
for +: 'datetime.time' and 'datetime.timedelta'), another exception 
occurred:  

How can I do this in Python 3?

like image 253
Teshan Nanayakkara Avatar asked Oct 27 '25 16:10

Teshan Nanayakkara


2 Answers

Try this:

from datetime import date, datetime, time, timedelta
dt = datetime.combine(date.today(), time(13, 0)) + timedelta(minutes=10)
print (dt.time())
#13:10:00
like image 102
ExplodingGayFish Avatar answered Oct 30 '25 08:10

ExplodingGayFish


Here's what you want:

import datetime

date = datetime.datetime.strptime('15:57:12', '%H:%M:%S')
print(date.strftime('%H:%M:%S'))
date = date+datetime.timedelta(seconds=1800)
print(date.strftime('%H:%M:%S'))
date = date+datetime.timedelta(minutes=30)
print(date.strftime('%H:%M:%S'))

Output:

15:57:12
16:27:12
16:57:12
like image 42
Strange Avatar answered Oct 30 '25 07:10

Strange



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!