get the date 5 years ago in python

You can get the date 5 years ago in Python by subtracting a timedelta of 5 years from the current date. Here's some code that does that:

main.py
import datetime

current_date = datetime.date.today()
five_years_ago = current_date - datetime.timedelta(days=5*365)

print(five_years_ago)
140 chars
7 lines

This code creates a datetime.date object to represent the current date (datetime.date.today()). It then subtracts a timedelta object that represents 5 years (multiplying the number of days in a year by 5). The resulting date is stored in the five_years_ago variable, which is printed to the console.

Note that this approach assumes that a year is exactly 365 days long, which is not always the case (leap years are 366 days long). For a more precise calculation, you can use the dateutil library instead of a fixed number of days in a year. Here's how you can do that:

main.py
import datetime
from dateutil.relativedelta import relativedelta

current_date = datetime.date.today()
five_years_ago = current_date - relativedelta(years=5)

print(five_years_ago)
181 chars
8 lines

This code uses the relativedelta function from dateutil to create a timedelta object representing 5 years. The years parameter specifies the number of years to subtract, which is 5 in this case. The resulting timedelta object is subtracted from the current date using the - operator, and the resulting date is stored in five_years_ago and printed to the console.

gistlibby LogSnag