Python Time Mastery: Datetime Formatting and Sleep Guide

Handling dates and times is one of the most common—yet often most frustrating—tasks for any Python developer. Whether you're scraping data, logging events, or building a web app, you need to know how to display time in a way that humans can read, and how to control the flow of your program with delays.

In this guide, we'll master the datetime module and the time module, focusing on strftime, strptime, and sleep.

1. Displaying Time: Using strftime

The strftime method (short for "string format time") allows you to convert a datetime object into a readable string. It uses specific "percent codes" to define the layout.

from datetime import datetime now = datetime.now() # Output format: 2024-02-07 14:30:00 print(now.strftime("%Y-%m-%d %H:%M:%S")) # Output format: February 07, 2024 (Wednesday) print(now.strftime("%B %d, %Y (%A)"))

Common strftime Codes

Code Meaning Example
%Y Year (4-digit) 2024
%m Month (01-12) 02
%d Day of Month 07
%B Month Name (Full) February
%A Weekday (Full) Wednesday
%H Hour (24-hour) 14
%M Minute 30

2. Reading Time: Using strptime

What if you have a string (like "2024-05-20") and want to turn it into a Python object? That's where strptime (short for "string parse time") comes in.

date_string = "20/05/2024" date_object = datetime.strptime(date_string, "%d/%m/%Y") print(date_object.year) # Out: 2024

Note: The format string you provide to strptime must exactly match the structure of your input string, otherwise Python will throw a ValueError.

3. Waiting Around: Using time.sleep

Sometimes you need your program to pause. This is common when you're waiting for a file to download, or to avoid hitting a website too fast while web scraping.

import time print("Starting task...") time.sleep(2.5) # Wait for 2.5 seconds print("Task finished after pause.")

Pro Tip: time.sleep() accepts floats, so you can wait for fractions of a second (like 0.1) for high-frequency tasks.

4. The "Big Data" Context: ISO 8601

If you're storing dates in a database, always use the ISO 8601 format: YYYY-MM-DDTHH:MM:SS. This format is internationally recognized and makes sorting a breeze. Python makes this easy:

print(datetime.now().isoformat()) # Out: 2024-02-07T14:30:05.123456

Conclusion

Time is a variable, but shouldn't be a mystery. By mastering strftime and strptime, you can move data seamlessly between humans and machines. And with time.sleep, you gain precise control over your program's timing.

Looking for more Python and data science tips? Check out our guides on Pandas, Algorithm Complexity, and Data Visualization at NumberInWord.com.