Monday, May 19, 2014

Number of days between two dates/ date differences in Python

To find the number of days between two given dates or to find the difference between two dates in Python. This function generally needs in many case in most of the program.

from datetime import datetime

def days_between(d1, d2):
    d1 = datetime.strptime(d1, "%Y-%m-%d")
    d2 = datetime.strptime(d2, "%Y-%m-%d")
    return abs((d2 - d1).days)

Example:

>>> from datetime import datetime
>>> d1 = '2014-05-10'
>>> d2 = '2014-05-05'
>>> d1 = datetime.strptime(d1, "%Y-%m-%d")
>>> d2 = datetime.strptime(d2, "%Y-%m-%d")
>>> no_of_days = abs((d2 - d1).days)
>>> no_of_days

Labels: , , ,


0 comments: Post Yours! Read Comment Policy ▼
PLEASE NOTE:
We have Zero Tolerance to Spam. Chessy Comments and Comments with Links will be deleted immediately upon our review.

 
Twitter Facebook RSS YouTube Google
© 2014 | Distributed and Designed By Jasad Moozhiyan