This is Day 16 of the #100DaysOfPython challenge.
- Familiarity with Pipenv. See here for my post on Pipenv.
- Familiarity with iPython or interactive shells.
Let’s create the
hello-python-datetimes directory and install the required dependencies.
We are now ready to begin exploring the standard
Playing around with dates and times
Start the shell with
pipenv shell ipython. This will activate the virtual shell and start an iPython interactive shell.
Now we are free to
from datetime import date and play around with it:
The above displays some of the common methods of the
date class. More information about the
date class can be found here.
A lot of what we want to do today is look at how to take some of these methods and get to a point where we can compare dates.
We want to write a helper method to check if a given date in the format
YYYY-MM-DD is before today. Exit the iPython kernel and add the following code to our
We can use the
< operators to compare dates.
If we now run
python src/datetimes.py we should see the following output:
We can see the output reflects a date string that is before today (with today returning
Working with now
datetime module from the
datetime library also has a
now method that returns the current date and time.
We can use this in combination with
strftime to get the current date and time in a string format. Update the code to the following:
python src/datetimes.py will output
To learn more about
strftime, there is a great blog post here.
Adding and subtracting dates
We can use
datetime.timedelta to add and subtract dates.
Update our code to the following:
Once again we will
python src/datetimes.py which will output the following:
Awesome, now we know how to add and subtract from dates!
Today’s post demonstrated how to use the
datetime module to compare times and determine the current date.
Dates and times are incredibly important to any temporal applications, and the following posts will spend some time looking further into this and how to write tests for this form of functionality.
Resources and further reading
Originally posted on my blog. To see new posts without delay, read the posts there and subscribe to my newsletter.