Last active
October 26, 2018 13:49
-
-
Save n0m4dz/ee41d4ca84e2630e70c6 to your computer and use it in GitHub Desktop.
python pretty time with localization
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
# coding: utf-8 | |
from datetime import datetime | |
from datetime import timedelta | |
def calc_diff(delta): | |
delta = abs( delta ) | |
return { | |
'year' : int(delta.days / 365), | |
'month' : int(delta.days % 365) / 30, | |
'day' : int(delta.days % 365) % 30, | |
'hour' : int(delta.seconds / 3600), | |
'minute' : int(delta.seconds / 60) % 60, | |
'second' : delta.seconds % 60, | |
'microsecond' : delta.microseconds | |
} | |
def localize(u): | |
return { | |
'year': 'жил', | |
'month' : 'сар', | |
'day': 'өдөр', | |
'hour': 'цаг', | |
'minute': 'минут', | |
'second': 'секунд', | |
'microsecond': 'микросекунд' | |
}.get(u, '') | |
def pretty_date(dt, length=3, past_tense='{}-н өмнө', future_tense='{}-н дараа '): | |
delta = dt | |
if type(dt) is not type(timedelta()): | |
delta = datetime.now() - dt | |
the_tense = past_tense | |
if delta < timedelta(0): | |
the_tense = future_tense | |
d = calc_diff( delta ) | |
hlist = [] | |
count = 0 | |
units = ( 'year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond' ) | |
for unit in units: | |
if count >= length: break | |
if d[ unit ] == 0: continue | |
l = localize(unit) | |
hlist.append( '%s %s' % ( d[unit], l ) ) | |
count += 1 | |
pretty_delta = ' '.join( hlist ) | |
return the_tense.format(pretty_delta) | |
date_past = datetime( | |
year = 2012, | |
month=6, | |
day=8, | |
hour=6, | |
minute=54, | |
second=33, | |
microsecond=4000 | |
) | |
date_future = datetime( | |
year = 2018, | |
month=10, | |
day=14, | |
hour=6, | |
minute=54, | |
second=33, | |
microsecond=4000 | |
) | |
print pretty_date(date_past, 3) | |
print pretty_date(date_future, 3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment