Last active
December 12, 2015 12:08
-
-
Save IlianIliev/4769940 to your computer and use it in GitHub Desktop.
Tweeter timeline time formatter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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