Printing Relative Dates in Python

posted July 11th 2006 at 1344 EDT in All, Python, Programming

introducing getRelativeTime() an easy way to say "in 4 days" or "4 days ago" from a timestamp.

Of course it's much easier to just show you what it does (and can do)


>>> from relativeDates import *
>>> import time
>>> x = time.time()-1000
>>> getRelativeTime(x)
'17 minutes ago'
>>> x-=12345
>>> getRelativeTime(x)
'3 hours ago'
>>> x+=543211
>>> getRelativeTime(x)
'in 6 days'
>>> getRelativeTime(x,accuracy=2)
'in 6 days 3 hours'
>>> x-=987661
>>> getRelativeTime(x,accuracy=2)
'5 days 7 hours ago'
>>> getRelativeTime(x,accuracy=2,alternative_past="long long ago")
'long long ago'
>>> getRelativeTimeStr("07/15/06 1823")
'in 4 days'
>>> getRelativeTimeStr("07/10/06 1823")
'7 hours ago'
>>> getRelativeTimeStr("07/10/06 1823",accuracy=2)
'7 hours 30 mins ago'
 

download relativeDates.py

Now for what it CAN'T do (yet). I won't do months or years because i didn't need them. It should be a good start for you though ;-)

3 Responses

  1. #1 faulkner
    1 year, 11 months ago

    http://home.comcast.net/~faulkner612/programming/python/when.py

  2. […] Jehiah has a function called getRelativeTime() that will make it really easy to do relative date printing, such as “4 days ago” or “in 2 days.” […]

  3. […] Эхия Чеботар написал getRelativeTime(), функцию для отображения относительной даты текстом, а я адаптировал эту функцию к русскому языку. […]

Leave a comment