Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
datetime / time
#1
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)
Reply
#2
the try/except block should not be indented.
Reply
#3
(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?
Reply
#4
(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
ifigazsi likes this post
Reply
#5
Quote:Ofc! But still why is the try part not working?
It is not working because it is not indented properly.
Reply
#6
(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'
ifigazsi and buran like this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Assign a value if datetime is in between a particular time limit klllmmm 2 2,748 Jan-02-2021, 07:00 AM
Last Post: klllmmm
  TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'str' findbikash 2 9,591 Sep-18-2019, 08:32 AM
Last Post: buran
  Convert from datetime to time.struct_time object chris0147 0 4,358 Mar-11-2018, 12:01 AM
Last Post: chris0147
  Subtract Minutes from Datetime.Time tkj80 2 43,032 May-11-2017, 09:56 AM
Last Post: klllmmm

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020