How do I calculate number of days between two dates using Python?

如果我有两个日期(例如'8/18/2008''9/26/2008' ),获得这两个日期之间的天数的最佳方法是什么?


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 = d1 - d0
print delta.days

The relevant section of the docs: https://docs.python.org/library/datetime.html


使用日期时间的力量:

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

Days until Christmas:

>>> import datetime
>>> today = datetime.date.today()
>>> someday = datetime.date(2008, 12, 25)
>>> diff = someday - today
>>> diff.days
86

More arithmetic here.

链接地址: http://www.djcxy.com/p/36706.html

上一篇: 我如何获得JavaScript中两个日期之间的天数?

下一篇: 如何使用Python计算两个日期之间的天数?