Back to Course

Intermediate Python

0% Complete
0/0 Steps
Lesson 16 of 33
In Progress

The Datetime Module

The datetime module is a built-in Python module that provides functions and classes for working with dates and times. It allows you to store and manipulate dates, times, and time intervals, and to convert between different representations of dates and times.

Datetime Objects

The datetime module provides several types of objects:

  • datetime: Represents a single point in time, with a year, month, day, hour, minute, second, and microsecond.
  • date: Represents a single day, with a year, month, and day.
  • time: Represents a time of day, with an hour, minute, second, and microsecond.
  • timedelta: Represents a duration or interval, with days, seconds, and microseconds.

The datetime module also provides several functions for creating and manipulating these objects:

  • datetime.now(): Returns the current date and time.
  • datetime.utcnow(): Returns the current date and time in UTC.
  • datetime.fromtimestamp(): Returns a datetime object from a Unix timestamp.
  • datetime.utcfromtimestamp(): Returns a datetime object from a Unix timestamp in UTC.
  • datetime.strptime(): Parses a string into a datetime object using a specified format.
  • datetime.strftime(): Formats a datetime object as a string using a specified format.

Datetime Operations

Here is an example of creating a datetime object and formatting it as a string:

import datetime

# create a datetime object for the current date and time
dt = datetime.datetime.now()
print(dt)  # Output: 2022-12-24 12:34:56.789012

# format the datetime object as a string
s = dt.strftime('%Y-%m-%d %H:%M:%S')
print(s)  # Output: 2022-12-24 12:34:56

In this example, the datetime.now() function returns the current date and time, and the strftime() function formats the datetime object as a string using the specified format.

You can also use the datetime module to perform arithmetic with dates and times, such as adding or subtracting intervals. For example:

import datetime

# create a datetime object for the current date and time
dt = datetime.datetime.now()

# add one day to the datetime object
dt2 = dt + datetime.timedelta(days=1)
print(dt2)  # Output: 2022-12-25 12:34:56.789012

# subtract one hour from the datetime object
dt3 = dt - datetime.timedelta(hours=1)
print(dt3)  # Output: 2022-12-24 11:34:56.789012

In this example, the timedelta object represents a duration of one day or one hour, and the + and - operators are used to add or subtract the duration from the datetime object.

You can also use the datetime module to convert between different representations of dates and times. For example, you can use the date() and time() attributes to get the date and time objects from a datetime object, and the combine() function to create a datetime object from a date and time object:

import datetime

# create a datetime object for the current date and time
dt = datetime.datetime.now()

# get the date and time objects from the datetime object
date = dt.date()
time = dt.time()

print(date)  # Output: 2022-12-24
print(time)  # Output: 12:34:56.789012

# create a datetime object from a date and time object
dt2 = datetime.datetime.combine(date, time)
print(dt2)  # Output: 2022-12-24 12:34:56.0

In this example, the date() and time() attributes return the date and time objects from the datetime object, and the combine() function creates a new datetime object from the date and time objects.

You can also use the datetime module to parse strings into datetime objects, using the strptime() function. For example:

import datetime

# parse a string into a datetime object
dt = datetime.datetime.strptime('2022-12-24 12:34:56', '%Y-%m-%d %H:%M:%S')
print(dt)  # Output: 2022-12-24 12:34:56

In this example, the strptime() function parses the string into a datetime object using the specified format.

Exercises

To review these concepts, we will go through a series of exercises designed to test your understanding and apply what you have learned.

Use the datetime module to create a datetime object for the current date and time, and format it as a string in the following format: ‘YYYY-MM-DD HH:MM:SS’.

import datetime

# create a datetime object for the current date and time
dt = datetime.datetime.now()

# format the datetime object as a string
s = dt.strftime('%Y-%m-%d %H:%M:%S')
print(s)  # Output: 2022-12-24 12:34:56

Use the datetime module to create a datetime object for the current date and time, and add one week to it.

import datetime

# create a datetime object for the current date and time
dt = datetime.datetime.now()

# add one week to the datetime object
dt2 = dt + datetime.timedelta(weeks=1)
print(dt2)  # Output: 2022-12-31 12:34:56.789012

Use the datetime module to parse the string ‘2022-12-24 12:34:56’ into a datetime object.

import datetime

# parse the string into a datetime object
dt = datetime.datetime.strptime('2022-12-24 12:34:56', '%Y-%m-%d %H:%M:%S')
print(dt)  # Output: 2022-12-24 12:34:56

Use the datetime module to create a timedelta object that represents a duration of 1 day and 2 hours.

import datetime

# create a timedelta object for 1 day and 2 hours
td = datetime.timedelta(days=1, hours=2)
print(td)  # Output: 1 day, 2:00:00

Use the datetime module to create a datetime object for the current date and time, and subtract the timedelta object from the previous exercise from it.

import datetime

# create a datetime object for the current date and time
dt = datetime.datetime.now()

# create a timedelta object for 1 day and 2 hours
td = datetime.timedelta(days=1, hours=2)

# subtract the timedelta object from the datetime object
dt2 = dt - td
print(dt2)  # Output: 2022-12-23 10:34:56.789012