Skip to content

Instantly share code, notes, and snippets.

@CheeseCake87
Created June 15, 2024 08:12
Show Gist options
  • Save CheeseCake87/f4a0ab9c2e8cbd59a4d3df30be76be58 to your computer and use it in GitHub Desktop.
Save CheeseCake87/f4a0ab9c2e8cbd59a4d3df30be76be58 to your computer and use it in GitHub Desktop.
import typing as t
from datetime import datetime
def calculate_days_between_dates(date: t.Union[str, datetime]) -> int:
"""
Calculates the days between a date and now
Date format must be in the format of %Y-%m-%d if date is a string
"""
if isinstance(date, datetime):
return (datetime.now() - date).days
return (datetime.now() - datetime.strptime(date, "%Y-%m-%d")).days
def calculate_persons_age(date_of_birth: t.Union[str, datetime]) -> int:
"""
Calculates a persons age from a date of birth
Date format must be in the format of %Y-%m-%d if date is a string
"""
if not isinstance(date_of_birth, datetime) and not isinstance(date_of_birth, str):
raise ValueError("Date of birth must be a string or datetime object")
if isinstance(date_of_birth, datetime):
return (datetime.now() - date_of_birth).days // 365
return (datetime.now() - datetime.strptime(date_of_birth, "%Y-%m-%d")).days // 365
def num_to_month(num) -> str:
months = {
0: "",
1: "January",
2: "February",
3: "March",
4: "April",
5: "May",
6: "June",
7: "July",
8: "August",
9: "September",
10: "October",
11: "November",
12: "December",
}
if isinstance(num, int):
if num in months:
return months[num]
return ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment