Skip to main content

timesince

Take two datetime objects and return the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, return "0 minutes".

Units used are years, months, weeks, days, hours, and minutes. Seconds and microseconds are ignored.

The algorithm takes into account the varying duration of years and months. There is exactly "1 year, 1 month" between 2013/02/10 and 2014/03/10, but also between 2007/08/10 and 2008/09/10 despite the delta being 393 days in the former case and 397 in the latter.

Up to depth adjacent units will be displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not.

time_strings is an optional dict of strings to replace the default TIME_STRINGS dict.

depth is an optional integer to control the number of adjacent time units returned.

Originally adapted from https://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since Modified to improve results for years and months.

def timesince(
d: datetime.date | datetime.datetime,
now: datetime.date | datetime.datetime = null,
reversed: boolean = false,
time_strings: dict = null,
depth: integer = 2
) - > string

Take two datetime objects and return the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, return "0 minutes".

Parameters

NameTypeDescription
d`datetime.datedatetime.datetime`
now`datetime.datedatetime.datetime` = null
reversedboolean = falseIf true, calculates the time from now to d instead of d to now.
time_stringsdict = nullAn optional dictionary of translation strings to override the default time unit labels.
depthinteger = 2The maximum number of adjacent time units to include in the output string.

Returns

TypeDescription
stringA human-readable string representing the elapsed time, such as "2 weeks, 3 days".