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:

Flowchart: Print next 5 days starting from today.

Python Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Python program to convert the date to datetime (midnight of the date).
Next: Write a Python program to add 5 seconds with the current time.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/date-time-exercise/python-date-time-exercise-9.php