How to add Days to a Date in Python?
Python provides an in-built module datetime which allows easy manipulation and modification of date and time values. It allows arithmetic operations as well as formatting the output obtained from the DateTime module. The module contains various classes like date, time, timedelta, etc. that simulate the easy implementation of dates and time (month, years, and days).
Date and time objects are created using the DateTime module which is immutable and hashable. The following classes of the DateTime module are used to add days to a date in python :
- datetime – DateTime objects give date along with time in hours, minutes, seconds. The DateTime library provides manipulation to a combination of both date and time objects (month, day, year, seconds and microseconds).
- timedelta – Timedelta class represents the duration. The DateTime library provides timedelta method to carry out date-related manipulation and also calculate differences in time objects. It can be majorly used to perform arithmetic operations like addition, subtraction, and multiplication. By specifying the days attribute value, we can add days to the date specified.
Syntax: datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Example 1: The following Python code is used to add days to a date in Python
Python3
from datetime import datetime from datetime import timedelta # taking input as the date Begindatestring = "2020-10-11" # carry out conversion between string # to datetime object Begindate = datetime.strptime(Begindatestring, "%Y-%m-%d" ) # print begin date print ( "Beginning date" ) print (Begindate) # calculating end date by adding 10 days Enddate = Begindate + timedelta(days = 10 ) # printing end date print ( "Ending date" ) print (Enddate) |
Output:
Beginning date 2020-10-11 00:00:00 Ending date 2020-10-21 00:00:00
Example 2: The program adds 10 days to the beginning date in yyyy-mm-dd format
Python3
from datetime import datetime from datetime import timedelta from datetime import date # taking input as the current date # today() method is supported by date # class in datetime module Begindatestring = date.today() # print begin date print ( "Beginning date" ) print (Begindatestring) # calculating end date by adding 4 days Enddate = Begindatestring + timedelta(days = 4 ) # printing end date print ( "Ending date" ) print (Enddate) |
Output:
Beginning date 2020-12-05 Ending date 2020-12-09
Contact Us