Python: Compute and Prettily Display Difference Between Two Dates

#!/usr/bin/env python

import calendar
import datetime
import dateutil
import dateutil.parser
import os
import sys

def usage():
    print "Usage: %s start-date end-date" % (os.path.basename(sys.argv[0]))

def diff_dates(start, end):

    months = (end.year - start.year)*12 + end.month - start.month
    years  = months / 12
    months = months % 12
    days   = end.day - start.day

    if days < 0:
        months -= 1
        if months < 0:
            months  = 11
            years  -= 1
        days = calendar.monthrange(end.year, end.month)[1] + end.day - start.day

    return (years, months, days)

def pretty_diff(datetuple):

    (years, months, days) = datetuple

    value = ''
    if years == 1:
        value = "%d year" % (years)
    elif years > 0:
        value = "%d years" % (years)

    if months > 0:
        if len(value) > 0:
            value += ", "
        if months == 1:
            value += "%d month" % (months)
        else:
            value += "%d months" % (months)

    if days > 0 or len(value) == 0:
        if len(value) > 0:
            value += ", "
        if days == 1:
            value += "%d day" % (days)
        else:
            value += "%d days" % (days)

    return value

if __name__ == "__main__":

    if len(sys.argv) < 3:
        usage()
        sys.exit()

    start = dateutil.parser.parse(sys.argv[1]).date()
    end   = dateutil.parser.parse(sys.argv[2]).date()

    if start > end:
        diff  = diff_dates(end, start)
        print pretty_diff(diff)
    else:
        diff  = diff_dates(start, end)
        print pretty_diff(diff)    
Advertisements
This entry was posted in Python and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s