How to add two datetime.datetime objects?

I want to add two datetime objects.

>>> from datetime import datetime >>> a = datetime.strptime("04:30",'%H:%M') >>> b = datetime.strptime("02:30",'%H:%M') >>> a datetime.datetime(1900, 1, 1, 4, 30) >>> b datetime.datetime(1900, 1, 1, 2, 30) 

when I subtract b from a, it gives me a way out

 >>> ab datetime.timedelta(0, 7200) 

but when i add a and b it gives me an error

 >>> a+b Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'datetime.datetime' 

I want to add time b to time a, that is, I want this.

 datetime.datetime(1900, 1, 1, 7, 00) 

please, help?

+5
source share
1 answer

Agreeing with the previous poster, there is no meaningful way to add two times, since they are just instants of time, you can only deal with the difference between them (timedeltas). Since you are not explicitly specifying dates in your example, it looks like it will be more in line with what you are trying to do:

 >>> a = datetime.timedelta(0, (4*3600+30*60)) >>> b = datetime.timedelta(0, (2*3600+30*60)) >>> a+b datetime.timedelta(0, 25200) >>> print a+b 7:00:00 

Since timedeltas takes days, seconds and microseconds, you need to multiply your hours and minutes to get them on the right basis.

+3
source

Source: https://habr.com/ru/post/1215144/


All Articles