Skip to content

Instantly share code, notes, and snippets.

@IlianIliev
Last active December 12, 2015 12:08
Show Gist options
  • Save IlianIliev/4769940 to your computer and use it in GitHub Desktop.
Save IlianIliev/4769940 to your computer and use it in GitHub Desktop.
Tweeter timeline time formatter
import unittest
from datetime import datetime, timedelta
from tweetime import timelinetime
class TimeLineTimeTest(unittest.TestCase):
def test_timelinetime(self):
now = datetime.now()
r = timelinetime(now -timedelta(seconds=5))
self.assertEqual(r, '5s')
r = timelinetime(now-timedelta(seconds=68))
self.assertEqual(r, '1m')
r = timelinetime(now-timedelta(seconds=3750))
self.assertEqual(r, '1h')
yesterday = now-timedelta(seconds=86450)
r = timelinetime(yesterday)
self.assertEqual(r, yesterday.strftime('%d %b'))
if __name__ == '__main__':
unittest.main()
from datetime import datetime
def timelinetime(dt):
""" Convert datetime object to string according to Twitters
requirement for displaying tweet time in timelines
https://dev.twitter.com/terms/display-requirements
With Django use django.utils.timezone.now() instead of datetime.now()
"""
now = datetime.now()
diff = abs((now-dt).total_seconds())
if diff < 60:
return '%ss' % int(round(diff))
if 60 <= diff < 3600:
return '%sm' % int(round(diff/60.0))
if 3600 <= diff < 86400:
return '%sh' % int(round(diff/3600.0))
if diff >= 86400:
return dt.strftime('%d %b')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment