Gmail Style Date Formatting In Python
I can format date with strftime in python, but now I want to show date in format relative to current time. i.e. if date is near today, show in time. if it is within week, show as
Solution 1:
There is a library
From the documentation,
[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]
Solution 2:
django.contrib.humanize.naturaltime
For datetime values, returns a string representing how many seconds, minutes or hours ago it was – falling back to a longer date format if the value is more than a day old. In case the datetime value is in the future the return value will automatically use an appropriate phrase.
Examples (when ‘now’ is 17 Feb 2007 16:30:00):
17Feb2007 16:30:00 becomesnow.17Feb2007 16:29:31 becomes29secondsago.17Feb2007 16:29:00 becomesaminuteago.17Feb2007 16:25:35 becomes4minutesago.17Feb2007 15:30:29 becomesanhourago.17Feb2007 13:31:29 becomes2hoursago.16Feb2007 13:31:29 becomes1dayago.17Feb2007 16:30:30 becomes29secondsfromnow.17Feb2007 16:31:00 becomesaminutefromnow.17Feb2007 16:34:35 becomes4minutesfromnow.17Feb2007 16:30:29 becomesanhourfromnow.17Feb2007 18:31:29 becomes2hoursfromnow.18Feb2007 16:31:29 becomes1dayfromnow.
You can get the sources here.
Post a Comment for "Gmail Style Date Formatting In Python"