Implement the same exercise as Exercise 1 (Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old), except don’t explicitly write out the year. Use the built-in Python
datetime library to make the code you write work during every year, not just the one we are currently in.
One very common thing programs are used for is to perform operations with dates and times. How hard is it for you to count the number of days between two dates? Or count the number of seconds between two specific times? Good thing someone else wrote code that already does this for us! Python distributes these other useful pieces of code as built-in libraries or modules. It comes standard with any Python installation, so no additional installation is required.
The built-in library in Python used for working with dates and times is called
datetime. The structures and functions in the library will be useful to solve the exercise.
To use a built-in library or module, we need to import this module into our current code. (For another use case for modules, see Exercise 9)
Now, we can use the
datetime library to construct dates and manipulate them. The full documentation for
datetime has a comprehensive list of functions available in this library, but I will highlight a few common ones.
To get today’s date, use the utility function:
which returns a
datetime object that we can manipulate. For example:
We can also take the delta between two times:
In the above sample code, we used
import time from the Python time library to pause the program for exactly 2 seconds.