Categories
Python Answers

How to add days to a date in Python?

Spread the love

Sometimes, we want to add days to a date in Python.

In this article, we’ll look at how to add days to a date in Python.

How to add days to a date in Python?

To add days to a date in Python, we can use the datetime.timedelta method and the + operator.

For instance, we write:

import datetime

start_date = '10/01/2021'
date_1 = datetime.datetime.strptime(start_date, "%m/%d/%Y")

end_date = date_1 + datetime.timedelta(days=10)
print(end_date)

We call datetime.datetime.strptime with start_date and the format string to convert the date string to a date object.

%m is the 2 digit month’s format code.

%d is the 2 digit day’s format code.

%Y is the 4 digit year’s format code.

Then we add 10 days to date_1 by using datetime.timedelta(days=10) to create the 10 days time delta object.

And then we use the + operator to add 10 days to date_1.

So end_date is 2021-10-11 00:00:00.

Conclusion

To add days to a date in Python, we can use the datetime.timedelta method and the + operator.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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