Printing Relative Dates in Python

by @jehiah on 2006-07-11 13:44UTC
Filed under: 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)

[python]
>>> 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'
[/python]

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 ;-)

Subscribe via RSS ı Email
© 2023 - Jehiah Czebotar