12

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.

Mauro Baraldi
  • 6,346
  • 2
  • 32
  • 43
  • You *could* subtract "1900-01-01 00:00:00" from your times to obtain deltas, but where are those `HrsEarly` coming from in the first place? They are not `HrsEarly`, but a specific point in time. Also, your code is not valid python (`AcDepart = 1900-01-01 18:00:00`) – Jasper Mar 23 '15 at 22:20

5 Answers5

7

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)
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • 1
    Great answer. Who knew that subtracting to datetime objects would instead return a timedelta object. It wasnt obvious to me! Thanks! – Hephaestus Apr 17 '18 at 16:58
4

Convert the string to timedelta

from datetime import datetime

AcDepart = '1900-01-01 18:00:00'
AcDepart_ = datetime.strptime(AcDepart, '%Y-%m-%d %H:%M:%S')
AcArrival = '1900-01-01 07:00:00'
AcArrival_ = datetime.strptime(AcArrival, '%Y-%m-%d %H:%M:%S')
ActualHours = (AcDepart_ - AcArrival_).total_seconds()/3600
print ActualHours
Larry Song
  • 1,086
  • 9
  • 13
3

It makes no sense to add two datetime objects: It might seem, in your example, that "2AM on the 1st of January 1900" plus "half past midnight on the 1st of January 1900" should be "half past two on the 1st of January 1900", but in another context the desired result could as easily be "half past two on the 2nd of February 3800", or even (if the UNIX epoch is used as an origin) "half past two on the first of January 1830".

Looking at a different example might make this more obvious: what should be the result of Tuesday + Saturday?

Your HrsEarly and HrsLate variables are presumably meant to store a time difference, and there's an appropriate type for that: datetime.timedelta. Adding two of those together does what you want:

>>> from datetime import timedelta
>>> HrsEarly = timedelta(hours=2)
>>> HrsLate = timedelta(minutes=30)
>>> HrsTotal = (HrsEarly + HrsLate)
>>> str(HrsTotal)
'2:30:00'
Community
  • 1
  • 1
Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
1

How about this method using built-in timestamp function?

import datetime

a = "2017-01-01 14:30:00"
b = datetime.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
c = b.timestamp()
d = datetime.timedelta(seconds=c)

Runtime environment
  OS: Ubuntu 16.04
  Python 3.6

Cloud Cho
  • 1,594
  • 19
  • 22
0

Create a modules.py and paste the following two functions. Import them wherever you want and use as is.

import datetime

def JsTimestampToPyDatetime(js_date):
    """
        converts javascript timestamp to python datetime taking care of 
        milliseconds and seconds

        Args:
            js_date(Timestamp, required)

        Returns:
            Datetime
    """

    try:
        # handles seconds
        date = datetime.datetime.fromtimestamp(int(js_date))
    except (ValueError):
        # handles miliseconds
        date = datetime.datetime.fromtimestamp(int(js_date) / 1000)
       
    return date

# consuming javascript generated timestamps

a = JsTimestampToPyDatetime(1627303810000) # with miliseconds
b = JsTimestampToPyDatetime(1627476610) # with seconds only


def GetDaysInDateTime(min_stamp, max_stamp):
    """
        Calculates time difference between two timestamps in days

        Args:
            min_stamp(Datetime, required): Minimum/start datetime
            max_stamp(Datetime, required): Maximum/end datetime

        Returns:
            Int: Days
    """

    days = (max_stamp-min_stamp).days
    return int(days)


print(GetDaysInDateTime(a, b))
Jet Ezra
  • 164
  • 2
  • 9