Converting datetime to timedelta so they can be added

user4490696 picture user4490696 · Mar 23, 2015 · Viewed 17.2k times · Source

When subtracting two datetime objects, I understand the result is timedelta object:

import datetime

AcDepart = 1900-01-01 18:00:00
AcArrival = 1900-01-01 07:00:00
ActualHours = AcDepart - AcArrival 

I want to then subtract the sum of two other date time objects from ActualHours

These are the two other objects:

HrsEarly = 1900-01-01 02:00:00
HrsLate = 1900-01-01 00:30:00

This is the equation that fails to complete:

UnCalcTime = ActualHours - (HrsEarly + HrsLate)

This is the error:

UnCalcTime = ActualHours - (HrsEarly + HrsLate)
TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'datetime.datetime'

So, I obviously can't add datetime.datetime. Does anyone know how I could get around this? Can timedelta be added together? If so, how can I convert datetime to timedelta?

Any help would be greatly appreciated as I have been trying to solve this unsuccessfully for a long time.

Answer

Mark Ransom picture Mark Ransom · Mar 23, 2015

The best solution is to create your variables as timedelta in the first place.

HrsEarly = datetime.timedelta(hours=2)
HrsLate = datetime.timedelta(minutes=30)

If you can't do that, you can simply subtract your "zero date" from the datetime objects.

>>> HrsEarly
datetime.datetime(1900, 1, 1, 2, 0)
>>> HrsEarly = HrsEarly - datetime.datetime(1900, 1, 1)
>>> HrsEarly
datetime.timedelta(0, 7200)