Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add two datetime.datetime objects?

Tags:

python

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 the output

>>> a-b
datetime.timedelta(0, 7200)

but, when i add a and b it gives me 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 the time of b to time of a, i.e i want this.

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

please help ?

like image 428
karan Avatar asked Mar 11 '15 13:03

karan


People also ask

Can we add two dates in Python?

For adding or subtracting date, we use something called timedelta() function which can be found under datetime class. It is used to manipulate date, and we can perform an arithmetic operations on date like adding or subtract.


1 Answers

Agreeing with the previous poster, there isn't a meaningful way to add two datetimes, as they're just points in time, you can only deal with the difference between them (timedeltas). Since you don't explicitly mention the dates in your example, this seems like it would be more along the lines of what you're trying to accomplish:

>>> 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

As timedeltas take days, seconds, and microseconds you need to multiply your hours and minutes to get them to the correct base.

like image 171
mattvivier Avatar answered Oct 23 '22 16:10

mattvivier