Dates and Times

PythonPythonBeginner
Practice Now

Introduction

The Python datetime module provides a range of classes for manipulating dates and times. In this lab, we will explore some of the most commonly used classes and functions from this module, and learn how to use them to perform a variety of tasks such as working with dates, times, and time deltas.

Achievements

  • datetime Module

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/date_time("`Date and Time`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/tuples -.-> lab-75{{"`Dates and Times`"}} python/importing_modules -.-> lab-75{{"`Dates and Times`"}} python/using_packages -.-> lab-75{{"`Dates and Times`"}} python/standard_libraries -.-> lab-75{{"`Dates and Times`"}} python/date_time -.-> lab-75{{"`Dates and Times`"}} python/build_in_functions -.-> lab-75{{"`Dates and Times`"}} end

Importing the Datetime Module

To start working with the datetime module, we first need to import it.

Open up a new Python interpreter session:

python3

This can be done using the following line of code:

import datetime

Working with Dates

The datetime module provides the date class for working with dates. To create a date object representing a specific date, we can use the date() constructor, which takes three arguments: the year, month, and day. For example:

d = datetime.date(2021, 12, 31)
print(d)

This will create a date object representing December 31st, 2021, and print it in the format "YYYY-MM-DD".

Working with Times

In addition to dates, the datetime module also provides the time class for working with times. To create a time object representing a specific time, we can use the time() constructor, which takes three arguments: the hour, minute, and second. For example:

t = datetime.time(12, 30, 15)
print(t)

This will create a time object representing 12:30:15 PM, and print it in the format "HH:MM:SS".

Combining Dates and Times

To work with both a date and a time, we can use the datetime class, which combines a date and a time. To create a datetime object representing a specific date and time, we can use the datetime() constructor, which takes six arguments: the year, month, day, hour, minute, and second. For example:

dt = datetime.datetime(2021, 12, 31, 12, 30, 15)
print(dt)

This will create a datetime object representing December 31st, 2021 at 12:30:15 PM, and print it in the format "YYYY-MM-DD HH:MM:SS".

Working with Timedeltas

In addition to working with specific dates and times, the datetime module also provides the timedelta class for working with time durations. A timedelta object represents a duration of time, and can be added or subtracted from a datetime object to produce a new datetime object. For example:

d1 = datetime.date(2021, 12, 31)
d2 = d1 + datetime.timedelta(days=1)
print(d2)

This will create a timedelta object representing one day, add it to the date object d1, and produce a new date object representing January 1st, 2022 and will print it in the format "YYYY-MM-DD".

Formatting Dates and Times

The datetime module provides the strftime() method, which can be used to format a datetime object as a string. This method takes a format string as an argument, which specifies the desired format of the output string. For example, the following code formats a datetime object as a string in the format "YYYY-MM-DD HH:MM:SS":

dt = datetime.datetime(2021, 12, 31, 12, 30, 15)
s = dt.strftime('%Y-%m-%d %H:%M:%S')
print(s)

It will print "2021-12-31 12:30:15"

Parsing Dates and Times from Strings

The datetime module also provides the strptime() class method, which can be used to parse a string and create a datetime object. This method takes two arguments: the string to be parsed, and a format string that specifies the expected format of the input string. For example, the following code parses a string in the format "YYYY-MM-DD HH:MM:SS" and creates a datetime object:

s = '2021-12-31 12:30:15'
dt = datetime.datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
print(dt)

It will print "2021-12-31 12:30:15"

The format string is a string of characters that correspond to the different parts of a date and time, such as the year, month, day, hour, minute, and second.

Here are some of the most commonly used characters in the format string:

  • %Y: year with century as a decimal number. For example, "2022"
  • %m: month as a zero-padded decimal number. For example, "01" for January, "12" for December
  • %d: day of the month as a zero-padded decimal number. For example, "01" for the first day of the month, "31" for the last day of the month
  • %H: hour (24-hour clock) as a zero-padded decimal number. For example, "00" for midnight, "12" for noon, "23" for 11 PM
  • %M: minute as a zero-padded decimal number. For example, "00" for the top of the hour, "30" for half past the hour
  • %S: second as a zero-padded decimal number. For example, "00" for the start of the minute, "59" for the end of the minute

In addition to these characters, the format string can also include literal characters that will be matched against the input string. For example, the following format string will match a date in the format "YYYY-MM-DD":

fmt = '%Y-%m-%d'

The strptime() method will then use this format string to parse the input string, and extract the year, month, and day from it.

It is important to note that the format string must match the input string exactly, otherwise an exception will be raised. If you are unsure about the format of the input string, you can use the try and except statements to handle any potential exceptions that may be raised.

Also, the strptime() method is not widely recommended due to some issues like it is not thread-safe and it is slow. It is recommended to use the dateutil.parser.parse() function, which is more flexible and more efficient.

Working with Time Zones

The datetime module also provides the pytz library that can be used to work with time zones. To use it, you will need to install it first by running pip install pytz in your command line.

Once installed, you can use the pytz.timezone function to create a timezone object for a specific time zone, for example:

from datetime import datetime
import pytz

dt = datetime.now(pytz.timezone('US/Pacific'))
print(dt)

This will create a datetime object with the current date and time in the Pacific Time (US) time zone, and print it in the format "YYYY-MM-DD HH:MM:SS-TZ".

Summary

In this lab, we have explored some of the most commonly used classes and functions from the Python datetime module, and learned how to use them to perform a variety of tasks such as working with dates, times, and timedeltas. We have seen how to create date, time and datetime objects using the appropriate constructors, and how to combine them to represent specific points in time. We also learned about the timedelta class, which can be used to represent durations of time, and how to use it to perform arithmetic operations on datetime objects.

In addition to the examples provided in this lab, the datetime module also provides a range of other functions and classes for working with timezones, formatting dates and times, and parsing dates and times from strings. It is a powerful and versatile module that can be used to solve a wide variety of time-related problems in Python.

In this lab, we have explored some of the advanced features of the Python datetime module, including date and time format conversion, and time zone conversion. We learned how to use the strftime() and strptime() methods to format and parse dates and times as strings, and how to use the pytz library to work with time zones. With these tools, you should be able to work effectively with dates and times in Python and solve a wide variety of time-related problems.

Other Python Tutorials you may like