Dates
Updated on 28 Dec 2022
Working with dates is always an important thing aspect of learning a new programming language. Python comes with a datetime module that needs to be imported into your script.
Today’s date
Let’s look at a basic example of printing today’s date. Now when I say “print out today’s date” I don’t mean look at the calendar and then use the print command with a hard-coded value of date. I mean, use Python to figure out the date and print that; so that if I run the script today, tomorrow or the next day - it will always print the current today’s date.
import datetime
today = datetime.date.today()
print('today\'s date: ' + str(today))
Formatting the date
We can have a date, but it can be represented in many different ways. Do we use numbers or names for the month? Jan or January, 1 or 01. No matter what format you want, we can still work with the same date
object in Python.
Python uses strftime.org for formatting dates. Go ahead and have a look at that resource see if it makes sense to the code and screen shot below.
import datetime
today = datetime.datetime.today()
print('today\'s date: ' + str(today))
formatted_date = today.strftime('%Y%m%d')
print('Formatted date: ' + str(formatted_date))
Info:
datetime.date.today()
returns the current date,datetime.datetime.today()
returns the current date with time
Creating a date from a string
There are going to be many situations where we need to create a date object from a string or variable. It could be hard-coded or even loaded from a file. So long as the string is a date and it matches your predefined pattern, then you’ll be able to create a date object from it.
For this example we already have a string that represents a date. This date could have been loaded from a text file, returned from a function or even API call. What we want to do is ‘reformat’ it to the date that we actually want; or what an api call might require. We will use datetime.strptime() to create a date object from a string.
import datetime
dateStr = '01/04/2019'
myDate = datetime.datetime.strptime(dateStr, '%d/%m/%Y')
print(myDate)
Date attributes
If we look at the datetime object documentation we can see an assortment of methods and attributes. Let’s extend the previous example.
dateStr = '01/04/2019'
myDate = datetime.datetime.strptime(dateStr, '%d/%m/%Y')
if myDate.month == 4:
print('Alert, it is April')
Another way of accomplishing this task is combining knowledge from previous sections with the following code:
dateStr = '01/04/2019'
myDate2 = datetime.datetime.strptime(dateStr, '%d/%m/%Y')
month = myDate2.strftime('%-m')
if month == '4':
print('Alert, it is April')
Either technique presented is acceptable.
Dates - guided exercise
I need to know if today’s date occurs AFTER the cutoff date. I might start off with some code that looks like this:
import datetime
today = datetime.datetime.today()
cutoff = '31/03/2019'
I can’t make a direct comparison between today
and cutoff
because one is a string and the other is an object. This would be the equivalent of trying to do the following equation. It makes no sense because you are trying to add a string and number together.
total = 'brent' + 12
Note: You CAN NOT make a direct comparison between a
date
object anddatetime
object
If we can convert cutoff
from a string to a datetime
object, then we can start making comparisons.
import datetime
today = datetime.datetime.today()
cutoff = '31/03/2019'
cutoff_date = datetime.datetime.strptime(cutoff, '%d/%m/%Y')
if today > cutoff_date:
print('Sorry, you did not make the cutoff date')
else:
print('Yay, you made the cutoff')
Dates - extended exercise
Use your knowledge you’ve learnt so far with time delta object to find the date 7 days from today’s date.