Add Years to datetime Object in Python

Add Years to datetime Object in Python

In Python, the datetime module does not have built-in functionality specifically for adding years to a datetime object. However, you can achieve this by using the dateutil.relativedelta class from the dateutil library, which allows you to add (or subtract) years, months, etc., from a datetime object.

Here's how you can do it:

1. Install the dateutil Library:

If you haven't already, you'll need to install the python-dateutil package:

pip install python-dateutil 

2. Use relativedelta to Add Years:

from datetime import datetime from dateutil.relativedelta import relativedelta # Current datetime dt = datetime.now() print("Original Date:", dt) # Add 2 years to the current datetime new_dt = dt + relativedelta(years=2) print("Date After 2 Years:", new_dt) # Subtract 3 years from the current datetime new_dt2 = dt - relativedelta(years=3) print("Date 3 Years Ago:", new_dt2) 

In this example, the relativedelta class is used to add or subtract years from a datetime object. You can similarly add/subtract days, months, hours, etc., using relativedelta.


More Tags

colors sublimetext3 swap primeng-turbotable gdal double-click-advertising django-queryset reactjs-testutils .net-standard compare

More Programming Guides

Other Guides

More Programming Examples