← Back to Posts

Python – Relative datetime formatting

I wanted a function in Python to get a relative datetime string formatting. For a given datetime object, it should be compared with the current date/time and a relative date/time format should be given as output.

For example, given a date/time lets say (July 2, 2007 7:00 pm) the output should be 7:00 pm Monday, while for October 3, 1980 6:00 am, it should give just 10/03/1980. I googled a lot, but didn’t get any code to copy. So I had to write my own. If anybody needs it from now on, you can take it from here.

#!/usr/bin/env python

from datetime import datetime

def getRelativeDateTime(date, now = None): 

    if not now:	now = datetime.now()

    diff = now.date() -­ date.date()

    if diff.days == 0:#Today

        return 'at ' + date.strftime("%I:%M %p")## at 05:45 PM

    elif diff.days == ­1:#Yesterday

        return 'at ' + date.strftime("%I:%M %p") + ' Yesterday'## at 05:45 PM Yesterday

    elif diff.days == -1:#Tomorrow

        return 'at ' + date.strftime("%I:%M %p") + ' Tomorrow'## at 05:45 PM Tomorrow

    elif diff.days < ­7:#Within one week back

        return 'at ' + date.strftime("%I:%M %p %A")## at 05:45 PM Tuesday

    else:

        return 'on ' + date.strftime("%m/%d/%Y")## on 10/03/1980