Chapter 7, Lesson 1 Text
Lesson One: Dates and Times
Python contains several useful tools for managing dates and times. In this lesson, you are going to learn how to create date and time objects that hold specific day and time values. You will then take advantage of Python's powerful formatting features to display that information to the screen in custom formats.
Most of Python's date and time functions are kept in the datetime module. Like the "pdb" debugger library, you need to import each module that you want to use at the top of your code.
Using the "datetime" Module
In order to use the datetime module, you must add the "import datetime" statement at the top of your code.
This module contains several useful objects, described in the table below.
|date||The date object manages a year, month and day and contains functions relating to the setting and display of these values.|
|time||The time object manages an hour, minute, second, microsecond and time zone and contains functions relating to the setting and display of these values.|
|datetime||The datetime object is basically a combination of date and time, and can fully represent an instant by full date and time.|
|timedelta||The timedelta object represents the difference between two date, time or datetime objects.|
|timezone||A timezone object can help display times in a local time zone.|
In Python, a "class" or "object" is an organized set of functions and data values that serve some specific purpose. You'll learn more about Object-Oriented-Programming (OOP) later in the course. For now, you can visualize an "object" as just another kind of data that is stored in a variable. But, instead of holding just a single raw value like 42 or "hello", an object might have many functions and data values that you can use.
Creating date, time and datetime Objects
A date, time or datetime object is stored in a variable, just like a regular number, string or list. Each variable holding a date, time or datetime object can hold a specific day (like March 16th, 2019), a specific time (like 1:30pm) or a specific date and time (March 16th, 2019 at 1:30pm).
You can create each one of these objects using an assignment statement as demonstrated below. Start by writing your variable name like myDate, then an equals sign, and then the datetime package name with a dot (.) afterwards. Next, use the name of the object you want to create as a function call with parentheses containing numeric parameters. Those numeric parameters set the specific date and/or time for your new object.
import datetime myDate = datetime.date(2019,3,16) # create a date object holding March 16, 2019 myTime = datetime.time(13,30,0) # create a time object holding 1:30pm myDateTime = datetime.datetime(2019,3,16,13,30,0) # create a datetime object holding both date and time
Calling datetime.date(), datetime.time(), or datetime.datetime() will create a date, time or datetime object. These functions are also called constructors because they build a new object and initialize it with data.
Let's take a closer look at the parameters for each of these constructor functions. You are passing in numeric values to represent the year, month, day and so on.
date(year, month, day) time(hours, minutes, seconds, microseconds) datetime(year, month, day, hours, minutes, seconds, microseconds)
The numbers you use for each of the parameter values must be valid. It does not make sense, for example, to use a negative month. The range of valid values is described below.
- year - an integer between 1 and 9999
- month - an integer between 1 and 12
- day - an integer between 1 and the actual number of days in the month
- hour - an integer between 0 and 23 (a 24-hour clock is used to set the hour)
- minute - an integer between 0 and 59
- second - an integer between 0 and 59
- microsecond - an integer between 0 and 999999
You can leave out the microsecond parameter and it will simply default to 0. You will rarely need to use microsecond-level timestamps.
Simple Printing of date, time and datetime Values
There are a great many ways that you might want to display a date or time value. For example, dates might be shown as "2019-03-16", "3/16/19", "March 26, 2019" or similar arrangements. Times might be shown in formats like "1:30 PM" (using a 12-hours clock with AM/PM) or "13:30:00" (24-hours clock including seconds at the end).
Python does have some functions that allow you to really fine-tune exactly how you want your dates and times to appear when printed to the screen. However, you can very easily display a default format, so let's start with that approach.
You can pass the date, time and datetime objects into the print() function just like you would any other variable. Python will convert the objects into display text. The date and datetime objects also have a function called ctime() that will show dates in a different format.
To call a function like ctime() on a variable that contains an object, simply write the variable name, a dot (.) and then the function name, followed by opening and closing parentheses. So, if you have initialized a variable named "myDate" with a date object, you can write "myDate.ctime()" to call the function on that object.
The example below creates each kind of object and then displays their values to the screen using the default format and ctime(), where available. Run the code to see each kind of output!
Try It Now
Try changing some of the input numbers used to build each object to create different dates and times. Then re-run the code to verify you are getting reasonable output.
The date, time and datetime objects each allow you to customize the printed display using the strftime() function. strftime() has a single string parameter that controls exactly how the data values will be shown.
import datetime myDateTime = datetime.datetime(2019,3,16,13,30,0) output = myDateTime.strftime("<format string>") # see below for format string description print(output)
The format string, conceptually, is similar to the format string you learned to use in str.format(). You can enter placeholders to insert values within other text. The table below shows some of the common placeholders and examples for strftime().
|%a||Day of the week as an abbreviation||Mon, Tue|
|%A||Day of the week as a full name||Monday, Tuesday|
|%d||Day of the month as a number||01 through 31|
|%b||Month as an abbreviation||Jan, Feb|
|%B||Month as a full name||January, February|
|%m||Month as a number||01 through 12|
|%y||Last two digits of a year||18, 19, 20|
|%Y||Full four-digit year||2018, 2019, 2020|
|%H||Hours on a 24-hour clock||01 through 23|
|%I||Hours on a 12-hour clock||01 through 12|
|%p||AM or PM on a 12-hour clcok||AM, PM|
|%M||Minute as a number||01 through 59|
|%S||Second as a number||01 through 59|
|%c||Full date and time displayed in a local format||Sat Mar 16 13:30:00 2019|
|%x||Date only, displayed in a local format||03/16/2018|
|%X||Time only, displayed in a local format||01:30:00|
So, in order to create a custom date or time display, you need to piece together a format string using some combination of the above placeholders. Can you predict how each of the following outputs will be formatted?
Try It Now
Run the code to see the results. You should see output as follows:
Saturday, March 16, 2019 30 minutes and 00 seconds 01 PM Sat Mar 16 13:30:00 2019 2019-03-16 01:30:00 PM
Go ahead and experiment on your own! You can change the initial datetime value or any of the strftime() format strings to produce new output.
If you are calling strftime() on a "date" object, then you can't use any of the placeholders relating to time, because hours, minutes and seconds are not available. Similarly, if you are using a "time" object, then you can't use any placeholders that produce date information.
Python contains two additional modules that focus on different areas of date and time management.
- time - This module contains a number of low-level system time functions.
- calendar - This module allows you to easily format and display calendars (e.g. a monthly calendar).
If you'd like to read more about these modules on your own, the official Python documentation can be found at the links below.
Work with Me: Your Birthday
You know the date of your birthday, but do you know the day of the week? In this exercise, you are going to find out if you were born on a Monday, Tuesday, or other day of the week. Follow the steps below to complete your code.
- Start by importing the datetime module
- Next, create a new "date" object called myBirthday and initialize it with the year, month and day of your birthday.
- Next, use strftime() to create the message "Your birthday is: YYYY/MM/DD" where YYYY is the year, MM is the month, and DD is the day. Print that message to the screen.
- Finally, use strftime() to create the message "You were born on a <DAY>", where <DAY> is the day of the week like "Monday" or "Tuesday". Print that message to the screen.
To use the strftime() function, you will use your date variable name (myBirthday) followed by a dot and then the function name, like this: myBirthday.strftime(...). The format string goes inside the parentheses.
Remember, the strftime() format string can contain any combination of fixed text like "Your birthday is:" and format placeholders like "%Y" to insert a 4-digit year in that location. strftime() will return the output string, which you can pass directly into the print() function.