Update get_top_billionaires.py

Fixed calculate_age function such that is returns the age correctly from a given timestamp. Fixed doctests to be robust when year changes
This commit is contained in:
Charlie Miller 2024-01-03 11:50:54 +00:00 committed by GitHub
parent c7866491ec
commit aae2164cb2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -20,36 +20,31 @@ API_URL = (
)
def calculate_age(unix_date: float) -> str:
def calculate_age(unix_timestamp: 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
72
>>> int(calculate_age(46915200000)) - years_since_create
50
>>> 2024 - int(calculate_age(946684800))
2000
>>> 2024 - int(calculate_age(-2145703316))
1902
>>> 2024 - int(calculate_age(2209202284))
2040
"""
# Convert date from milliseconds to seconds
unix_date /= 1000
birth_date = datetime.fromtimestamp(unix_timestamp, tz=UTC)
if unix_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()
return str(
TODAY.year
- birthdate.year
- ((TODAY.month, TODAY.day) < (birthdate.month, birthdate.day))
# Calculate the age
current_date = datetime.now(tz=UTC)
age = (
current_date.year -
birth_date.year -
((current_date.month, current_date.day) < (birth_date.month, birth_date.day))
)
return str(age)
def get_forbes_real_time_billionaires() -> list[dict[str, str]]: