Python add one year to date

Add one year in current date PYTHON

Sometimes we need to add a specific amount of time to the current date in Python, and one of the most common cases is adding one year to the current date. In this guide, we will explore different ways to add one year to the current date in Python.

Using the datetime library

One way to add one year to the current date is by using the `datetime` library, which provides several classes for working with dates and times. Here’s an example:

import datetime current_date = datetime.date.today() one_year_later = current_date.replace(year=current_date.year + 1) print("Current date:", current_date) print("One year later:", one_year_later) 

In this code, we first get the current date using the `today()` method of the `date` class. Then, we create a new date object by replacing the year of the current date with the current year plus one. Finally, we print both dates to the console.

Using the relativedelta module

Another way to add one year to the current date is by using the `relativedelta` module, which provides more advanced date calculations. Here’s an example:

import datetime from dateutil.relativedelta import relativedelta current_date = datetime.date.today() one_year_later = current_date + relativedelta(years=1) print("Current date:", current_date) print("One year later:", one_year_later) 

In this code, we first import the `relativedelta` class from the `dateutil` module. Then, we get the current date as before. Finally, we create a new date object by adding a `relativedelta` object that specifies a one-year difference in the `years` attribute.

Читайте также:  Передача значений переменных

Both methods will produce the same output, which will be the current date and the same date with one year added.

That’s it! You now know how to add one year to the current date in Python using two different methods. Feel free to choose the one that suits your needs best.

Источник

Python add one year to date

Last updated: Feb 18, 2023
Reading time · 4 min

banner

# Add year(s) to a date in Python

Use the datetime.replace() method to add years to a date.

The replace method will return a new date with the same attributes, except for the year, which will be updated according to the provided value.

Copied!
from datetime import datetime, date def add_years(start_date, years): try: return start_date.replace(year=start_date.year + years) except ValueError: # 👇️ preserve calendar day (if Feb 29th doesn't exist, set to 28th) return start_date.replace(year=start_date.year + years, day=28) # ✅ add years to a date my_str = '09-14-2023' # 👉️ (mm-dd-yyyy) date_1 = datetime.strptime(my_str, '%m-%d-%Y') print(date_1) # 👉️ 2023-09-14 00:00:00 result_1 = add_years(date_1, 3) print(result_1) # 👉️ 2026-09-14 00:00:00 # ----------------------------------------------- # ✅ add years to the current date current_date = datetime.today() print(current_date) # 👉️ 2023-02-18 18:57:28.484966 result_2 = add_years(current_date, 2) print(result_2) # 👉️ 2025-02-18 18:57:28.484966

add years to date

The add_years function takes the date and the number of years we want to add and returns an updated date.

The datetime.replace method returns an object with the same attributes, except for the attributes which were provided by keyword arguments.

In the examples, we return a new date where the month and the day are the same but the year is updated.

The first example uses the datetime.strptime() method to get a datetime object that corresponds to the provided date string, parsed according to the specified format.

Once we have the datetime object, we can use the replace() method to replace the year.

Copied!
from datetime import datetime, date def add_years(start_date, years): try: return start_date.replace(year=start_date.year + years) except ValueError: # 👇️ preserve calendar day (if Feb 29th doesn't exist, set to 28th) return start_date.replace(year=start_date.year + years, day=28) # ✅ add years to a date my_str = '09-14-2023' # 👉️ (mm-dd-yyyy) date_1 = datetime.strptime(my_str, '%m-%d-%Y') print(date_1) # 👉️ 2023-09-14 00:00:00 result_1 = add_years(date_1, 3) print(result_1) # 👉️ 2026-09-14 00:00:00

The date string in the example is formatted as mm-dd-yyyy .

If you have a date string that is formatted in a different way, use this table of the docs to look up the format codes you should pass for the second argument to the strptime() method.

Since we preserve the month and day of the month, we have to be aware that February has 29 days during a leap year, and it has 28 days in a non-leap year.

# The current date might be February 29th

The current date might be February 29th and adding X years returns a non-leap year where February 29th is not a valid date.

In this scenario, we update the year and set the day of the month to the 28th.

Copied!
def add_years(start_date, years): try: return start_date.replace(year=start_date.year + years) except ValueError: # 👇️ preserve calendar day (if Feb 29th doesn't exist, set to 28th) return start_date.replace(year=start_date.year + years, day=28)

An alternative approach is to set the date to March 1st if February 29th doesn’t exist in that year.

Copied!
from datetime import datetime, date def add_years(start_date, years): try: return start_date.replace(year=start_date.year + years) except ValueError: # 👇️ preserve calendar day (if Feb 29th doesn't exist # set to March 1st) return start_date + ( date(start_date.year + years, 1, 1) - date(start_date.year, 1, 1) ) # ✅ add years to a date my_str = '02-29-2024' # 👉️ (mm-dd-yyyy) date_1 = datetime.strptime(my_str, '%m-%d-%Y') print(date_1) # 👉️ 2024-02-29 00:00:00 result_1 = add_years(date_1, 3) print(result_1) # 👉️ 2027-03-01 00:00:00

the current date might be february 29

# Adding years to the current date

The second example adds years to the current date.

Copied!
from datetime import datetime, date def add_years(start_date, years): try: return start_date.replace(year=start_date.year + years) except ValueError: return start_date.replace(year=start_date.year + years, day=28) current_date = datetime.today() print(current_date) # 👉️ 2023-07-22 20:24:47.538361 result_2 = add_years(current_date, 2) print(result_2) # 👉️ 2025-07-22 20:24:47.538361

The datetime.today() method returns the current local datetime .

# Only extract the date components

If you only need to extract the date after the operation, call the date() method on the datetime object.

Copied!
from datetime import datetime, date def add_years(start_date, years): try: return start_date.replace(year=start_date.year + years) except ValueError: # 👇️ preserve calendar day (if Feb 29th doesn't exist # set to March 1st) return start_date + ( date(start_date.year + years, 1, 1) - date(start_date.year, 1, 1) ) now = datetime.now() print(now) # 👉️ 2023-02-18 18:59:48.402212 result = add_years(now, 1) print(result) # 👉️ 2024-02-18 18:59:48.402212 # 👇️ only get a date object print(result.date()) # 👉️ 2024-02-18

# Formatting the date

If you need to format the date in a certain way, use a formatted string literal.

Copied!
from datetime import datetime, date def add_years(start_date, years): try: return start_date.replace(year=start_date.year + years) except ValueError: return start_date + ( date(start_date.year + years, 1, 1) - date(start_date.year, 1, 1) ) now = datetime.now() print(now) # 👉️ 2023-02-18 19:00:11.870596 result = add_years(now, 1) print(result) # 👉️ 2024-02-18 19:00:11.870596 # 👇️ format the date print(f'result:%Y-%m-%d %H:%M:%S>') # 👉️ 2024-02-18 19:00:11

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f .

Make sure to wrap expressions in curly braces — .

Formatted string literals also enable us to use the format specification mini-language in expression blocks.

# Add years to a date using the date() class

You can also use the date() class instead of the datetime class when adding years to a date.

Copied!
from datetime import date def add_years(start_date, years): try: return start_date.replace(year=start_date.year + years) except ValueError: return start_date.replace(year=start_date.year + years, day=28) date_3 = date(2023, 9, 7) print(date_3) # 👉️ 2023-09-07 result_3 = add_years(date_3, 5) print(result_3) # 👉️ 2028-09-07

Here is an example that adds years to a date object that represents the current date.

Copied!
from datetime import datetime, date def add_years(start_date, years): try: return start_date.replace(year=start_date.year + years) except ValueError: return start_date.replace(year=start_date.year + years, day=28) # ✅ add years to current date (using date instead of datetime) date_4 = date.today() print(date_4) # 👉️ 2022-06-20 result_4 = add_years(date_4, 6) print(result_4) # 👉️ 2028-06-20

The date.today method returns a date object that represents the current local date.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How To Add Year(s) To The Current Date In Python

Add year(s) to the current date in Python

How to add year(s) to the current date in Python is an interesting topic in Python, perhaps very useful for those who are new to Python. Here are some suggestions for you. Let’s read this article now.

Add year(s) to the current date in Python

Use the replace() function

  • old: Original string.
  • new: String will replace the original string.
  • count: Specifies the maximum number of character substitutions.
  • Import datetime module.
  • Initialize the current date.
  • Add years using replace() in conjunction with strftime(), which returns a string representing the date, time, and date values.
import datetime dateNow = datetime.date.today() yearsToAdd = dateNow.year + 2 currentDate = dateNow.strftime('%Y-%m-%d') # Use the replace() function to add years resultDate = dateNow.replace(year=yearsToAdd).strftime('%Y-%m-%d') print('Current date:', currentDate) print('Date after adding:', resultDate)
Current date: 2022-10-25 Date after adding: 2024-10-25

Use DateOffset method

You also can use DateOffset() method from the pandas module to add years to the current year.

  • Import pandas module DateOffset() method of that module.
  • Initialize a datetime string.
  • Then you have to convert the datetime string to a datetime object.
  • Finally, use DateOffset() to add years to the current year.
import pandas as pd # String datetime currentDate = '2022-10-25' print('Current date: ' + currentDate) # Combine the pd.to_datetime function and the pd.DateOffset function to add year to the currentDate newDate = pd.to_datetime(currentDate) + pd.DateOffset(years = 2) print('Date after adding : ' + str(newDate))
Current date: 2022-10-25 Date after adding : 2024-10-25 00:00:00

Use the timedelta64 method

The datetime object is taken from the Python standard library so the object is named datetime64. You can use this to add years to the current year.

Timedelta64 is just a 64-bit integer that is interpreted in different ways depending on the second parameter you passed in.

  • Import the numpy module.
  • Create a datetime object using the datetime64() method.
  • Use the timedelta64() method to add years to the current year.
import numpy as np print('Date current: ' + str(np.datetime64('2022'))) # Use the timedelta64() method to add years to the current year newDate = np.datetime64('2022') + np.timedelta64(2, 'Y') print('Date after adding: ' + str(newDate))
Date current: 2022 Date after adding: 2024

Use relativedelta method

Relative styles are designed to be applied to existing dates and times and can replace specific components of that date or time or represent a period.

  • Import the datetime module to be able to use the date class.
  • Import the datetime module to be able to use the relativedelta method.
  • Initialize a datetime object using date().
  • Add years with the relativedelta() method.
from datetime import date from dateutil.relativedelta import relativedelta # The datetime object is created print('Current date: ' + str(date(2022,10,25))) # Add years using the relativedelta() method newDate = date(2022,10,25) + relativedelta(years=2) print('Date after adding: ' + str(newDate))
Current date: 2022-10-25 Date after adding: 2024-10-25

Summary

Hopefully, this article will give you more ideas about how to add year(s) to the current date in Python. You should read the article carefully to understand the problem I want to convey more deeply. If you have any questions, please leave a comment, and I will try to answer.

Maybe you are interested:

My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.

Name of the university: HHAU
Major: IT
Programming Languages: C++, Python, Java

Источник

Оцените статью