Chapter 11: Date and Time
Working with date and time, in this chapter of Mastering Python Fundamentals, is an essential part of many programming tasks, whether you’re logging events, scheduling tasks, or handling time zones. Python provides several modules to make these tasks easier, with the datetime
module being the most commonly used. This chapter will guide you through the basics of working with date and time in Python, including getting the current date and time, formatting dates, working with time zones, and manipulating dates and times.
11.1 Getting the Current Date and Time
The datetime
module allows you to easily get the current date and time. This can be useful for logging, timestamping events, or any situation where you need to know the current time.
11.1.1 Using datetime.now()
Example: Getting the Current Date and Time
from datetime import datetime
# Get the current date and time
now = datetime.now()
print(f"Current date and time: {now}")
Step-by-Step Guide:
- Open your text editor.
- Type the code above into your editor.
- Save the file as
current_datetime.py
. - Run the program by typing:
python current_datetime.py
- The output will display the current date and time, such as:
Current date and time: 2024-08-22 15:45:30.123456
11.2 Formatting Dates and Times
Formatting dates and times is crucial when you need to display them in a particular format or when you need to parse date strings.
11.2.1 Using strftime()
for Formatting
Example: Formatting the Current Date and Time
from datetime import datetime
# Get the current date and time
now = datetime.now()
# Format the date and time
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted date and time: {formatted_date}")
Step-by-Step Guide:
- Open your text editor.
- Type the code above into your editor.
- Save the file as
formatted_datetime.py
. - Run the program by typing:
python formatted_datetime.py
- The output will display:
Formatted date and time: 2024-08-22 15:45:30
11.2.2 Common Date and Time Formatting Directives
Here are some common formatting directives used with strftime()
:
%Y
: Year with century (e.g., 2024)%m
: Month as a zero-padded decimal number (e.g., 08)%d
: Day of the month as a zero-padded decimal number (e.g., 22)%H
: Hour (24-hour clock) as a zero-padded decimal number (e.g., 15)%M
: Minute as a zero-padded decimal number (e.g., 45)%S
: Second as a zero-padded decimal number (e.g., 30)
11.3 Parsing Dates and Times
Sometimes, you’ll need to convert a string representation of a date into a datetime
object. The strptime()
function allows you to do this.
11.3.1 Using strptime()
Example: Parsing a Date String
from datetime import datetime
# Define a date string
date_string = "2024-08-22 15:45:30"
# Parse the date string into a datetime object
parsed_date = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(f"Parsed date and time: {parsed_date}")
Step-by-Step Guide:
- Open your text editor.
- Type the code above into your editor.
- Save the file as
parsing_datetime.py
. - Run the program by typing:
python parsing_datetime.py
- The output will display:
Parsed date and time: 2024-08-22 15:45:30
11.4 Time Zones
Python’s pytz
library allows you to work with time zones. You can convert times between different time zones, making it easier to handle global applications.
11.4.1 Installing the pytz
Library
To work with time zones, you’ll need to install the pytz
library.
Command:
pip install pytz
11.4.2 Converting Between Time Zones
Example: Converting UTC to Eastern Time
from datetime import datetime
import pytz
# Define time zones
utc = pytz.utc
eastern = pytz.timezone('US/Eastern')
# Get the current time in UTC
now = datetime.now(utc)
print(f"Current time in UTC: {now}")
# Convert UTC time to Eastern time
eastern_time = now.astimezone(eastern)
print(f"Current time in US/Eastern: {eastern_time}")
Step-by-Step Guide:
- Install the
pytz
library using the command:
pip install pytz
- Open your text editor.
- Type the code above into your editor.
- Save the file as
timezone_conversion.py
. - Run the program by typing:
python timezone_conversion.py
- The output will display:
Current time in UTC: 2024-08-22 19:45:30.123456+00:00
Current time in US/Eastern: 2024-08-22 15:45:30.123456-04:00
11.5 Working with Timestamps
Timestamps represent the number of seconds that have passed since January 1, 1970 (the Unix epoch). They are useful for storing date and time information in a compact format.
11.5.1 Getting the Current Timestamp
Example: Getting the Current Timestamp
from datetime import datetime
# Get the current timestamp
timestamp = datetime.timestamp(datetime.now())
print(f"Current timestamp: {timestamp}")
Step-by-Step Guide:
- Open your text editor.
- Type the code above into your editor.
- Save the file as
current_timestamp.py
. - Run the program by typing:
python current_timestamp.py
- The output will display:
Current timestamp: 1727023530.123456
11.5.2 Converting a Timestamp to a datetime
Object
Example: Converting Timestamp to Date and Time
from datetime import datetime
# Define a timestamp
timestamp = 1727023530.123456
# Convert timestamp to datetime
dt_object = datetime.fromtimestamp(timestamp)
print(f"Datetime from timestamp: {dt_object}")
Step-by-Step Guide:
- Open your text editor.
- Type the code above into your editor.
- Save the file as
timestamp_to_datetime.py
. - Run the program by typing:
python timestamp_to_datetime.py
- The output will display:
Datetime from timestamp: 2024-08-22 15:45:30.123456
11.6 Time Delays and Sleeping
The time
module provides the sleep()
function, which can be used to pause the execution of a program for a specified amount of time.
11.6.1 Using sleep()
for Time Delays
Example: Pausing Execution for 5 Seconds
import time
# Pause execution for 5 seconds
print("Waiting for 5 seconds...")
time.sleep(5)
print("5 seconds have passed.")
Step-by-Step Guide:
- Open your text editor.
- Type the code above into your editor.
- Save the file as
time_delay.py
. - Run the program by typing:
python time_delay.py
- The output will display:
Waiting for 5 seconds...
5 seconds have passed.
Conclusion
This chapter has introduced you to working with date and time in Python, including how to get the current date and time, format and parse dates, work with time zones, handle timestamps, and create time delays. These are essential skills for any programmer, especially when dealing with real-world applications where accurate timekeeping and manipulation are crucial. Keep practicing the examples provided to deepen your understanding and become proficient in handling date and time in Python.