add specific number of days to a given date in python

To add a specific number of days to a given date in python.you can use the date and time modulate. which provides convenient classes for manipulating dates and times.

A specific number of days given date using the datetime module

1.importing required modules

2. define initial dates

3. Convert initial date to date time object

4. Convert initial date to date time object

5. Calculate new date

6. Convert new day to string

Importing required modules:

  • datetime for working with dates and Times
  • Time delta to represent a duration specifically a time difference

Define initial dates:

  • Initial _date_str is the initial date given as a string in ‘YYYY_MM_DD’ format

Convert initial date to datetime object:

Days_to_add is the number of days you want to add to initial_date

Convert initial date to datetime object:

Initial_date is obtained by using datetime. Strptime( ) to convert initial_date_str to a datetime object

Calculate new date:

  • New_date is calculated by adding days_to_add days to initial _date using time delta(days=days_to_add)

Convert new date to string:

  • New_date_str is obtained by formatting new_date back to YYYY_MM_DD' format using strftime (‘%y_%m_%d’)

This approach is straight forward and leverages python’s boit-in datetime handling capabilities to ensure accurate date calculation.adjust input _date and num_days as per your specific requirement to add days to any given date.

def add_days_to_date(input_date,
days_to_add):
   try:
     input_datetime=datetime.strptime(input _date,"%y_%m_%d")
     new_date=input_datetime+time delta
(days=days_to_add)
     new _date_str=new_date.strftime
("%y_%m_%d")
     Print(f"orginal date:
{input _date}")
     Print (f"new date after adding
{days _to_add}days:{new _date_str}")
Except value error:
     Print ("error: incorrect data 
format.please use YYYY_MM_DD")
     Input_date="2024-06-24"
     Example date
     days_to_add=5
     Of days to add
     add_days_to_date(input _date,
     days_to_add)
      

This program is flexible and can be adjusted to

handle different date formates or input validation based on specific needs.

Output:

Original date:2024-06-24

New date after adding 5 days:

2024-06-29

 

 

 

 

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top