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.py140 chars7 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.py181 chars8 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