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
Begindatestring = "2020-10-11"
Begindate = datetime.strptime(Begindatestring, "%Y-%m-%d" )
print ( "Beginning date" )
print (Begindate)
Enddate = Begindate + timedelta(days = 10 )
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
Begindatestring = date.today()
print ( "Beginning date" )
print (Begindatestring)
Enddate = Begindatestring + timedelta(days = 4 )
print ( "Ending date" )
print (Enddate)
|
Output:
Beginning date
2020-12-05
Ending date
2020-12-09
Last Updated :
29 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...