mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-03-26 08:29:48 +00:00
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:
parent
c7866491ec
commit
aae2164cb2
@ -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.
|
"""Calculates age from given unix time format.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Age as string
|
Age as string
|
||||||
|
|
||||||
>>> from datetime import datetime, UTC
|
>>> from datetime import datetime, UTC
|
||||||
>>> years_since_create = datetime.now(tz=UTC).year - 2022
|
>>> 2024 - int(calculate_age(946684800))
|
||||||
>>> int(calculate_age(-657244800000)) - years_since_create
|
2000
|
||||||
72
|
>>> 2024 - int(calculate_age(-2145703316))
|
||||||
>>> int(calculate_age(46915200000)) - years_since_create
|
1902
|
||||||
50
|
>>> 2024 - int(calculate_age(2209202284))
|
||||||
|
2040
|
||||||
"""
|
"""
|
||||||
# Convert date from milliseconds to seconds
|
# Convert date from milliseconds to seconds
|
||||||
unix_date /= 1000
|
birth_date = datetime.fromtimestamp(unix_timestamp, tz=UTC)
|
||||||
|
|
||||||
if unix_date < 0:
|
# Calculate the age
|
||||||
# Handle timestamp before epoch
|
current_date = datetime.now(tz=UTC)
|
||||||
epoch = datetime.fromtimestamp(0, tz=UTC)
|
age = (
|
||||||
seconds_since_epoch = (datetime.now(tz=UTC) - epoch).seconds
|
current_date.year -
|
||||||
birthdate = (
|
birth_date.year -
|
||||||
epoch - timedelta(seconds=abs(unix_date) - seconds_since_epoch)
|
((current_date.month, current_date.day) < (birth_date.month, birth_date.day))
|
||||||
).date()
|
|
||||||
else:
|
|
||||||
birthdate = datetime.fromtimestamp(unix_date, tz=UTC).date()
|
|
||||||
return str(
|
|
||||||
TODAY.year
|
|
||||||
- birthdate.year
|
|
||||||
- ((TODAY.month, TODAY.day) < (birthdate.month, birthdate.day))
|
|
||||||
)
|
)
|
||||||
|
return str(age)
|
||||||
|
|
||||||
|
|
||||||
def get_forbes_real_time_billionaires() -> list[dict[str, str]]:
|
def get_forbes_real_time_billionaires() -> list[dict[str, str]]:
|
||||||
|
Loading…
x
Reference in New Issue
Block a user