📅  最后修改于: 2023-12-03 15:33:59.036000             🧑  作者: Mango
Python has a powerful built-in module called datetime
which allows you to work with dates and times easily. In this article, we will discuss how to use Python to get the current date and add a specified number of days to it.
The first thing we need to do is to import the datetime
module. Once we have done that, we can use the date.today()
method to get the current date.
import datetime
current_date = datetime.date.today()
print(current_date)
Output:
2021-10-14
As you can see, the output is in the YYYY-MM-DD
format.
Now that we have the current date, we can use the timedelta
class to add a specified number of days to it. The timedelta
class represents a duration, the difference between two dates or times.
import datetime
current_date = datetime.date.today()
days_to_add = 5
new_date = current_date + datetime.timedelta(days=days_to_add)
print(new_date)
Output:
2021-10-19
In the above code, we have added 5 days to the current date using the timedelta
class.
In this article, we have discussed how to use Python to get the current date and add a specified number of days to it. The datetime
module in Python provides a lot of functionality for working with dates and times.