Python Forum

Full Version: datetime / time
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi!

The code is below, i got the solution, i'm just curious why
datetime.time + datetime.timedelta is not working...


import datetime

t = datetime.time(7, 0)
d = datetime.datetime(2021, 1, 1, 7, 0)
min_delta = datetime.timedelta(minutes=45)
try:
    print(t+min_delta)
except:
    print('Error')
    x = (d+min_delta)
    x = x.strftime("%H:%M")
    print(x)
the try/except block should not be indented.
(Jan-31-2021, 07:44 PM)Larz60+ Wrote: [ -> ]the try/except block should not be indented.

Ofc! But still why is the try part not working?
(Jan-31-2021, 07:31 PM)ifigazsi Wrote: [ -> ]'m just curious why
datetime.time + datetime.timedelta is not working...
datetime.time objects do not support addition with datetime.timedelta
Use datetime.datetime type with timedelta.
>>> from datetime import datetime, timedelta, time
>>> 
>>> d = datetime(2021, 1, 1, 7, 0)
>>> new_date = d + timedelta(hours=7)
>>> new_date
datetime.datetime(2021, 1, 1, 14, 0)
>>> 
>>> print(d)
2021-01-01 07:00:00
>>> print(new_date)
2021-01-01 14:00:00
Can also call time() if do i like this.
>>> print((d + timedelta(hours=7)).time())
14:00:00
>>> print(d.time())
07:00:00
Quote:Ofc! But still why is the try part not working?
It is not working because it is not indented properly.
(Feb-01-2021, 12:45 AM)Larz60+ Wrote: [ -> ]It is not working because it is not indented properly.
He has edit his post and fixed indentation.
The reason why it not work now is what i explain in my post.

Just one more point ifigazsi you should not use bare except:
Now it hide the real error and just print error,which tell you nothing.
import datetime

t = datetime.time(7, 0)
d = datetime.datetime(2021, 1, 1, 7, 0)
min_delta = datetime.timedelta(minutes=45)
print(t + min_delta)
Error:
Traceback (most recent call last): File "<module4>", line 6, in <module> TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'