Days between 2 Dates

bumsfeld 0 Tallied Votes 488 Views Share

The Python module datetime allows you to calculate the days between two given dates with relative ease. I am using the US date format month/day/year, but you can change that by giving attention to the order of the extracted tuple.

# find the days between 2 given dates
# tested with Python25           HAB

import datetime as dt

# US format month/day/year
dateStr1 = '7/14/2006'
dateStr2 = '5/1/2007'

m1, d1, y1 = (int(x) for x in dateStr1.split('/'))
m2, d2, y2 = (int(x) for x in dateStr2.split('/'))

date1 = dt.date(y1, m1, d1)
date2 = dt.date(y2, m2, d2)

dateDiff = date2 - date1
print 'Difference in days = %d' % dateDiff.days  # 291