0

So in my project I'm trying to calculate a stock transaction and one of the fields requires me to subtract dates 04/15/2018 (buy date) 04/27/2018 (sell date) but, I'm not sure how to go about subtracting.

I've tried to subtract like 04/15/2018-04/27/2018, but since that wouldn't logically make sense I'm unsure of how to do this.

3 Answers3

1

Turn them into dates then you can simply subtract, see datetime.datetime.strptime(), e.g.:

In []:
from datetime import datetime
d1 = datetime.strptime('04/15/2018', '%m/%d/%Y')
d2 = datetime.strptime('04/27/2018', '%m/%d/%Y')
d1 - d2

Out[]:
datetime.timedelta(days=-12)`
AChampion
  • 29,683
  • 4
  • 59
  • 75
0

You will want to take a deeper look at the datetime package in the standard library. Another useful package would be dateutil which has some higher-level parsing functions.

You could do something like

start_date = "04/15/2018"  # note that this is a string
end_date = "04/27/2018"

from dateutil.parser import parse
start_dt = parse(start_date)
end_dt = parse(end_date)

time_delta = end_dt - start_dt

# get the time between the two dates in different units
days_between_dates = time_delta.days
seconds_between_dates = time_delta.total_seconds()
Andrew F
  • 2,690
  • 1
  • 14
  • 25
0

Borrowing from this answer Difference between two dates in Python the datetime.datetime.strptime module can do the date calculation:

from datetime import datetime

def days_between(d1, d2):
    d1 = datetime.strptime(d1, '%m/%d/%Y')
    d2 = datetime.strptime(d2, '%m/%d/%Y')
    return abs((d2 - d1).days)  # ensures a positive return value

print(days_between('04/15/2018', '04/27/2018'))

output:

12