Calendar Arithmetic (Python)

vegaseat 2 Tallied Votes 846 Views Share

The module datetime allows you to call several functions that can do computation with dates and times. How many days since my birth? How many days till Xmas? What's the date 77 days from now? The code snippet should give you a flavor, enough to explore on your own.

# testing (or tasting) the module datetime and its method date
# datetime supports calendar arithmetic
# strftime() requires the year to be >=1900
# date() can handle years down to 0001
# Python24 tested   vegaseat  3/27/05

import datetime
import calendar

today = datetime.date.today()
oneday = datetime.timedelta(days=1)
# loop back to most recent Friday (could be today)
# takes care of end of month and even leap years
friday = today
while friday.weekday() != calendar.FRIDAY:
    friday -= oneday
oneweek = datetime.timedelta(days=7)
nextweek = today + oneweek
nextyear = today.replace(year=today.year+1)
print "Today (year-month-day) =", today
print "Most recent Friday =", friday
print "One week from today =", nextweek
print "One year from today =", nextyear
print "Current time =", datetime.datetime.now().time()  #just the time
print "Lunchtime =", datetime.time(12, 00)              # 12:00:00

print '-'*50

# a typical birthday year, month, day
# or change it to your own birthday...
birthday = datetime.date(1955, 4, 1)
# three different ways to present a date
# 1955-04-01
print "Birthday format1:", birthday
# 04/01/55
print "Birthday format2:", birthday.strftime("%m/%d/%y")
# 01Apr1955
print "Birthday format3:", birthday.strftime("%d%b%Y")

age = today - birthday
print "You are", age.days, "days old today!"

# extract the year from todays date
thisyear = int(today.strftime("%Y")[0:4])

# party message (include date and time) ...
rightnow = datetime.datetime.today()
bparty = datetime.datetime(thisyear, 4, 1, 14, 30)
# check if you can still make it to the party ...
if bparty > rightnow:
    print "Birthday party", bparty
else:
    print "Missed this year's birthday party!"

print '-'*50

# calculate days till xmas of this year
xmas = datetime.date(thisyear, 12, 25)
tillXmas = xmas - today
print "There are %d days till xmas!" % tillXmas.days

print '-'*50

# add days to a given date
delta = datetime.timedelta(days=77)
addDays = today + delta
print "Today's date is               :", today.strftime("%d%b%Y")
print "77 days from today it will be :", addDays.strftime("%d%b%Y")

print '-'*50

Weekday = ['Monday', 'Tuesday', 'Wednesday', 'Thursday',
  'Friday', 'Saturday', 'Sunday']
print "Today is", Weekday[datetime.date.weekday(today)]
print
print "If you were born on %s you were born on a %s" % (birthday.strftime("%d%b%Y"), Weekday[datetime.date.weekday(birthday)])

Dani AI

Generated

Good, compact starter from . The snippet is a useful exploration of date arithmetic; below are small, practical improvements and gotchas for modern Python (safe one‑line patterns, leap‑day handling, a simple age-in-years helper, and notes on formatting/timezones).

from datetime import date, timedelta
import calendar

today = date.today()
days_since_friday = (today.weekday() - calendar.FRIDAY) % 7
most_recent_friday = today - timedelta(days=days_since_friday)

This computes the most recent Friday in O(1) (no loop), and naturally crosses month/year boundaries.

Adding a year by calling replace(year=...) can fail for Feb 29. Use dateutil.relativedelta to handle this reliably (or fall back in a try/except):

# pip install python-dateutil
from dateutil.relativedelta import relativedelta
next_year = today + relativedelta(years=1)

# fallback without third-party lib
try:
    next_year = today.replace(year=today.year + 1)
except ValueError:
    # example policy: move Feb 29 -> Feb 28 next year
    next_year = date(today.year + 1, 2, 28)

To get an age in full years (not just days), use the common year-difference trick:

def age_in_years(birth, on=None):
    on = on or date.today()
    return on.year - birth.year - ((on.month, on.day) < (birth.month, birth.day))

Formatting and timezones: prefer simple f-strings for stable formatting of very old dates (avoids some platform strftime limits), and use zoneinfo (Python 3.9+) or dateutil.tz/pytz for timezone-aware datetimes when local time matters. These small patterns make the original examples more robust in real programs.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.