Last active
April 30, 2025 23:54
-
-
Save Pinacolada64/85d3fcac998dc01c937e0a4201e6e910 to your computer and use it in GitHub Desktop.
Practicing datetime module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import datetime | |
def time_delta_in_words(d1: datetime, d2: datetime): | |
years = abs(d1.year - d2.year) | |
months = abs(d1.month - d2.month) | |
# if d1.month - d2.month < 12 then less than an entire year between events. therefore subtract a year | |
if months < 12: | |
years -= 1 | |
print(f"less than 12 months between deltas, years now {years=}") | |
days = abs(d1.day - d2.day) | |
past_or_future = "ago" if d2 < d1 else "from now" | |
collective = [] | |
if years: | |
collective.append(f"{years} year{'s' if years != 1 else ''}") | |
if months: | |
collective.append(f"{months} month{'s' if months != 1 else ''}") | |
if days: | |
collective.append(f"{days} day{'s' if days != 1 else ''}") | |
collective.append(past_or_future) | |
print(', '.join(collective)) | |
if __name__ == '__main__': | |
date = datetime.now() | |
# Wed Apr 30, 2025 04:31:51 PM | |
print(date.strftime("%a %b %d, %Y %I:%M:%S %p")) | |
# https://docs.python.org/3/library/datetime.html#format-codes | |
# calculate year, month, day delta between date_born and date_today | |
birthday = datetime(1976, 6, 16) | |
today = datetime.now() | |
time_delta = today - birthday | |
print(time_delta) | |
# 49 years, 2 months, 14 days, ago | |
time_delta_in_words(today, birthday) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm not sure if that fixes other cases, but it is something to note