Python Forum

Full Version: Can't substract seconds from time
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi

iam novice to python.I can't understand where i did the mistake & why. Kindly correct my code.

#Write a Python program to add 5 seconds with the current time.
import datetime
t1 = datetime.datetime.now().time()
print("Current time:", t1)
t=t1+datetime.timedelta(seconds = 5)
print("After 5 Seconds:", t)
When i execute the above code iam getting "TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'".

Thank you
Don't try to add time() objects. Instead do your math with datetime() objects and then convert to time for display if you need.

#Write a Python program to add 5 seconds with the current time.
import datetime
t1 = datetime.datetime.now()  # stays a datetime object
print("Current time:", t1.time())
t=t1+datetime.timedelta(seconds = 5)
print("After 5 Seconds:", t.time())