forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_top_billionaires.py
More file actions
Latest commit
98 lines (78 loc) · 2.76 KB
/
Copy pathget_top_billionaires.py
File metadata and controls
98 lines (78 loc) · 2.76 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
"""
CAUTION: You may get a json.decoding error.
This works for some of us but fails for others.
"""
fromdatetimeimportUTC, datetime, timedelta
importrequests
fromrichimportbox
fromrichimportconsoleasrich_console
fromrichimporttableasrich_table
LIMIT=10
TODAY=datetime.now()
API_URL= (
"https://www.forbes.com/forbesapi/person/rtb/0/position/true.json"
"?fields=personName,gender,source,countryOfCitizenship,birthDate,finalWorth"
f"&limit={LIMIT}"
)
defcalculate_age(unix_date: float) ->str:
"""Calculates age from given unix time format.
Returns:
Age as string
>>> from datetime import datetime, UTC
>>> years_since_create = datetime.now(tz=UTC).year - 2022
>>> int(calculate_age(-657244800000)) - years_since_create
73
>>> int(calculate_age(46915200000)) - years_since_create
51
"""
# Convert date from milliseconds to seconds
unix_date/=1000
ifunix_date<0:
# Handle timestamp before epoch
epoch=datetime.fromtimestamp(0, tz=UTC)
seconds_since_epoch= (datetime.now(tz=UTC) -epoch).seconds
birthdate= (
epoch-timedelta(seconds=abs(unix_date) -seconds_since_epoch)
).date()
else:
birthdate=datetime.fromtimestamp(unix_date, tz=UTC).date()
returnstr(
TODAY.year
-birthdate.year
- ((TODAY.month, TODAY.day) < (birthdate.month, birthdate.day))
)
defget_forbes_real_time_billionaires() ->list[dict[str, str]]:
"""Get top 10 realtime billionaires using forbes API.
Returns:
List of top 10 realtime billionaires data.
"""
response_json=requests.get(API_URL).json()
return [
{
"Name": person["personName"],
"Source": person["source"],
"Country": person["countryOfCitizenship"],
"Gender": person["gender"],
"Worth ($)": f"{person['finalWorth'] /1000:.1f} Billion",
"Age": calculate_age(person["birthDate"]),
}
forpersoninresponse_json["personList"]["personsLists"]
]
defdisplay_billionaires(forbes_billionaires: list[dict[str, str]]) ->None:
"""Display Forbes real time billionaires in a rich table.
Args:
forbes_billionaires (list): Forbes top 10 real time billionaires
"""
table=rich_table.Table(
title=f"Forbes Top {LIMIT} Real Time Billionaires at {TODAY:%Y-%m-%d %H:%M}",
style="green",
highlight=True,
box=box.SQUARE,
)
forkeyinforbes_billionaires[0]:
table.add_column(key)
forbillionaireinforbes_billionaires:
table.add_row(*billionaire.values())
rich_console.Console().print(table)
if__name__=="__main__":
display_billionaires(get_forbes_real_time_billionaires())