﻿ Python: Print next 5 days starting from today - w3resource

# Python: Print next 5 days starting from today

## Python datetime: Exercise-9 with Solution

Write a Python program to print the next 5 days starting today.

Sample Solution:

Python Code:

``````# Import the datetime module
import datetime

# Get the current date and time and assign it to the variable 'base' using datetime.datetime.today()
base = datetime.datetime.today()

# Iterate over a range of 5 days starting from 0
for x in range(0, 5):
# Print the date and time by adding 'x' days to the base date using datetime.timedelta(days=x)
print(base + datetime.timedelta(days=x))
```
```

Output:

```2017-05-06 12:27:53.632939
2017-05-07 12:27:53.632939
2017-05-08 12:27:53.632939
2017-05-09 12:27:53.632939
2017-05-10 12:27:53.632939
```

Explanation:

In the exercise above,

• The code imports the "datetime" module, which provides functionalities to work with dates and times.
• Get the base date and time:
• It gets the current date and time using datetime.datetime.today() and assigns it to the variable 'base'.
• Looping over days:
• It iterates over a range of 5 days starting from 0 using a "for" loop with the "range(0, 5)" function call.
• In each iteration, it prints the date and time by adding the current iteration value (representing the number of days to add) to the base date using "base + datetime.timedelta(days=x)".
• This "timedelta" object adds 'x' days to the base date, effectively giving the date 'x' days in the future from the base date.
• Finally it prints the resulting date and time for each iteration, representing the current date and time plus 'x' days.

Flowchart:

Python Code Editor: