Chapter 7, Lesson 1 Text

Lesson One: Dates and Times

 

Calendar and clock iconPython 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.

import datetime

This module contains several useful objects, described in the table below.

ObjectDescription
dateThe date object manages a yearmonth and day and contains functions relating to the setting and display of these values.
timeThe time object manages an hourminutesecondmicrosecond and time zone and contains functions relating to the setting and display of these values.
datetimeThe datetime object is basically a combination of date and time, and can fully represent an instant by full date and time.
timedeltaThe timedelta object represents the difference between two datetime or datetime objects.
timezonetimezone 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

datetime or datetime object is stored in a variable, just like a regular number, string or list. Each variable holding a datetime 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 datetime 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 datetime 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

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
print("myDate =",myDate) # let print() convert to default format
print("myTime =",myTime) # let print() convert to default format
print("myDateTime =",myDateTime) # let print() convert to default format
print("myDate.ctime() = ",myDate.ctime()) # use ctime() for alternate format
print("myDateTime.ctime() = ",myDateTime.ctime()) # use ctime() for alternate format

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.

Advanced Printing

The datetime 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().

PlaceholderDescriptionExample
%aDay of the week as an abbreviationMon, Tue
%ADay of the week as a full nameMonday, Tuesday
%dDay of the month as a number01 through 31
%bMonth as an abbreviationJan, Feb
%BMonth as a full nameJanuary, February
%mMonth as a number01 through 12
%yLast two digits of a year18, 19, 20
%YFull four-digit year2018, 2019, 2020
%HHours on a 24-hour clock01 through 23
%IHours on a 12-hour clock01 through 12
%pAM or PM on a 12-hour clcokAM, PM
%MMinute as a number01 through 59
%SSecond as a number01 through 59
%cFull date and time displayed in a local formatSat Mar 16 13:30:00 2019
%xDate only, displayed in a local format03/16/2018
%XTime only, displayed in a local format01: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

import datetime
myDateTime = datetime.datetime(2019,3,16,13,30,0)
print(myDateTime.strftime("%A, %B %d, %Y"))
print(myDateTime.strftime("%M minutes and %S seconds"))
print(myDateTime.strftime("%I %p"))
print(myDateTime.strftime("%c"))
print(myDateTime.strftime("%Y-%m-%d %I:%M:%S %p"))

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.

 

Other Modules

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.

https://docs.python.org/3.3/library/time.html

https://docs.python.org/3.3/library/calendar.html


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.

  1. Start by importing the datetime module
  2. Next, create a new "date" object called myBirthday and initialize it with the year, month and day of your birthday.
  3. 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.
  4. 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.


Last modified: Sunday, 18 August 2019, 9:29 PM