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
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
Beginning date 2020-12-05 Ending date 2020-12-09
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course