If I have two dates (ex. '8/18/2008' and '9/26/2008') what is the best way to get the difference measured in days?
+35
A:
If you have two date objects, you can just subtract them.
from datetime import date
d0 = date(2008,8,18)
d1 = date(2008, 9, 26)
delta = d0 - d1
print delta.days
The relevant section of the docs: http://docs.python.org/lib/module-datetime.html
Dana
2008-09-29 23:41:22
+9
A:
Using the power of datetime:
from datetime import datetime
date_format = "%m/%d/%Y"
a = datetime.strptime('8/18/2008', date_format)
b = datetime.strptime('9/26/2008', date_format)
delta = b - a
print delta.days # that's it
dguaraglia
2008-09-29 23:41:59
LOL, someone posted almost *exactly* the same, but using date instead of datetime
dguaraglia
2008-09-29 23:42:54
actually, the date class would be more appropriate in this case than datetime.
Jeremy Cantrell
2008-09-30 15:08:59
+3
A:
You want the datetime module.
>>> from datetime import datetime
>>> datetime(2008,08,18) - datetime(2008,09,26)
datetime.timedelta(4)
Or other example:
Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53)
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> today = datetime.date.today()
>>> print today
2008-09-01
>>> last_year = datetime.date(2007, 9, 1)
>>> print today - last_year
366 days, 0:00:00
As pointed out here
kolrie
2008-09-29 23:43:10