-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprintRelTime.py
More file actions
75 lines (64 loc) · 2.83 KB
/
Copy pathprintRelTime.py
File metadata and controls
75 lines (64 loc) · 2.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
from datetime import datetime as _datetime, timezone as _timezone
second = 1.0
minute = second * 60
hour = minute * 60
day = hour * 24
month = day * 30
year = day * 365
week = day * 7
_timeNamesDict: dict[str, tuple[str, tuple[tuple[str]]]] = {
"pol": (
" temu",
(
("sekund", "minut", "godzin", "dni", "miesięcy", "lat"),
("sek" , "min" , "godz" , "dni", "mies" , "lat"),
("s" , "m" , "g" , "d" , "M" , "l" ),
)
),
"ang": (
" ago",
(
("seconds", "minutes", "hours", "days", "months", "years"),
("sec" , "min" , "hour" , "days", "mon" , "year" ),
("s" , "m" , "h" , "d" , "M" , "y" ),
)
),
}
def toFixed(num, dec = "0"):
return format(num, f".{dec}f")
def getRelTime(
epoch_s : float | _datetime = 0 ,
czyDiff : bool = True ,
lang : str = "ang",
compact : int = 0 ,
space : str = " " ,
ago : bool = True ,
leftAlign : bool = False,
prec : str = None ,
):
epoch_s = epoch_s.timestamp() if isinstance(epoch_s, _datetime) else epoch_s
czas = (_datetime.now(_timezone.utc).timestamp() - epoch_s) if czyDiff else epoch_s
znak = "-" if czas < 0 else ""
czas = abs(czas)
prec0 = "0" if prec is None else prec
prec1 = "1" if prec is None else prec
try:
agoStr, timeNamesArr = _timeNamesDict[lang]
timeNames = timeNamesArr[compact]
except:
raise Exception("Language not supported")
if leftAlign:
maxLen = max(timeNames, key=len)
timeNames = tuple(map(lambda x: x.ljust(maxLen), timeNames))
if czas < minute: czytCzas = toFixed(czas / second, prec0) + space + timeNames[0]
elif czas < hour : czytCzas = (toFixed(czas / minute, prec1) if czas <= minute * 9.95 else toFixed(czas / minute, prec0)) + space + timeNames[1]
elif czas < day : czytCzas = (toFixed(czas / hour , prec1) if czas <= hour * 9.95 else toFixed(czas / hour , prec0)) + space + timeNames[2]
elif czas < month : czytCzas = (toFixed(czas / day , prec1) if czas <= day * 9.95 else toFixed(czas / day , prec0)) + space + timeNames[3]
elif czas < year : czytCzas = (toFixed(czas / month , prec1) if czas <= month * 9.95 else toFixed(czas / month , prec0)) + space + timeNames[4]
else : czytCzas = (toFixed(czas / year , prec1) if czas <= year * 9.95 else toFixed(czas / year , prec0)) + space + timeNames[5]
return znak + czytCzas + (agoStr if ago else "")
if __name__ == "__main__": # Example usage
from myLibs.printRelTime import getRelTime
# from myLibs.printRelTime import day, getRelTime, hour, minute, month, second, week, year
print(getRelTime())
print(getRelTime(1000000000))