Master Dates and Times in Python with the datetime Module!
To run Python from the command prompt or PowerShell on your PC, you need to download and install Python.
If you haven’t installed it yet, please refer to the article Setting Up Python and Development Environment to install Python.
When developing websites and applications, you'll often need to handle dates and times, like displaying the current time, recording when an article was posted, or calculating the time remaining in a sale. That's where Python's built-in datetime module comes in handy.
In this article, we'll explain everything from the basics of the datetime module to some advanced techniques, with easy-to-understand sample code that even beginners can copy and paste to experience it "just working." Let's dive into the world of dates and times! 🚀
The ABCs of the datetime Module
First, let's start with how to set up the datetime module and its most basic function: getting the current date and time.
Importing the Module
To use the datetime module, you first need to import (load) it at the beginning of your code. Without this, Python will ask, "What is datetime?"
import datetime
Getting the Current Date and Time
Getting the current date and time is very simple. Just call `datetime.datetime.now()`.
import datetime
# Get the current date and time
now = datetime.datetime.now()
print(now)
# Example output: 2025-07-11 07:42:15.123456
If you don't need the time and just want today's date, use `datetime.date.today()`.
import datetime
# Get just today's date
today = datetime.date.today()
print(today)
# Example output: 2025-07-11
Accessing Individual Date and Time Elements
From the `datetime` object you've retrieved, you can extract individual pieces of information like the year, month, day, hour, minute, and second. This is useful, for example, when you want to display something like "The current year is 2025."
import datetime
now = datetime.datetime.now()
print(f"Year: {now.year}")
print(f"Month: {now.month}")
print(f"Day: {now.day}")
print(f"Hour: {now.hour}")
print(f"Minute: {now.minute}")
print(f"Second: {now.second}")
print(f"Microsecond: {now.microsecond}")
Creating a Specific Date and Time
Of course, you can also create objects representing a specific date and time in the past or future, not just the current time. This is used to specify things like your birthday or a service launch date.
import datetime
# Specify 9:30:00 AM on January 1, 2026
specific_datetime = datetime.datetime(2026, 1, 1, 9, 30, 0)
print(specific_datetime)
# Output: 2026-01-01 09:30:00
Formatting Dates and Times for Readability
A format like `2025-07-11 07:42:15` isn't bad, but on a website, you might want to display it more clearly, like "July 11, 2025, 07:42 AM". That's when the `strftime()` method comes in handy.
Converting to a String with a Custom Format using strftime()
`strftime()` stands for "string format time" and it converts a `datetime` object into a string with a specific format. To specify the format, you use "format codes" like `%Y` and `%m`.
import datetime
now = datetime.datetime.now()
# Convert to a string with a specified format
formatted_string = now.strftime("%B %d, %Y %I:%M:%S %p")
print(formatted_string)
# Example output: July 11, 2025 07:42:15 AM
Here are some commonly used format codes:
- `%Y`: Year with century (e.g., 2025)
- `%y`: Year without century (e.g., 25)
- `%m`: Month as a zero-padded decimal number (01-12)
- `%d`: Day of the month as a zero-padded decimal number (01-31)
- `%H`: Hour (24-hour clock) as a zero-padded decimal number (00-23)
- `%I`: Hour (12-hour clock) as a zero-padded decimal number (01-12)
- `%p`: Locale’s equivalent of either AM or PM.
- `%M`: Minute as a zero-padded decimal number (00-59)
- `%S`: Second as a zero-padded decimal number (00-59)
- `%A`: Locale’s full weekday name (e.g., Friday)
- `%a`: Locale’s abbreviated weekday name (e.g., Fri)
Converting a String to a Datetime with strptime()
Conversely, you might want to convert string data like "2025/07/11" into a `datetime` object that your program can work with. In that case, use the `strptime()` method. It stands for "string parse time" and helps parse strings.
Important: When using `strptime()`, the format of the original string and the format code you specify must match perfectly. If they don't match, you'll get an error, so be careful.
import datetime
date_string = "July 11, 2025"
# Convert the string to a datetime object by specifying its format
# In this example, since it's just a date, it becomes a date object
date_obj = datetime.datetime.strptime(date_string, "%B %d, %Y").date()
print(date_obj)
print(type(date_obj))
# Output:
# 2025-07-11
# <class 'datetime.date'>
Advanced: Let's Calculate with Dates and Times
The real power of the datetime module lies in its ability to easily perform calculations with dates and times. You can intuitively perform calculations like "What's the date one week from now?" or "How many days until the sale ends?" using `timedelta` objects.
Expressing Time Differences with timedelta
A `timedelta` is an object that represents a duration, the difference between two dates or times. You create it by specifying days, seconds, microseconds, etc.
import datetime
now = datetime.datetime.now()
print(f"Current time: {now.strftime('%Y-%m-%d %H:%M')}")
# Calculate one week later
one_week_later = now + datetime.timedelta(weeks=1)
print(f"One week from now: {one_week_later.strftime('%Y-%m-%d %H:%M')}")
# Calculate 3 days ago
three_days_ago = now - datetime.timedelta(days=3)
print(f"3 days ago: {three_days_ago.strftime('%Y-%m-%d %H:%M')}")
# Calculate 10 hours and 30 minutes from now
ten_hours_later = now + datetime.timedelta(hours=10, minutes=30)
print(f"10h 30m from now: {ten_hours_later.strftime('%Y-%m-%d %H:%M')}")
Calculating the Difference Between Two Dates
When you subtract one `datetime` object from another, the result is a `timedelta` object. You can use this to calculate the number of days remaining until a specific date.
import datetime
# Today's date
today = datetime.date.today()
# Target date (e.g., New Year's Day 2026)
new_year_2026 = datetime.date(2026, 1, 1)
# Calculate the difference between the two dates
delta = new_year_2026 - today
print(f"There are {delta.days} days until New Year's Day 2026.")
A Point of Caution: The Timezone Trap
The datetimes we've handled in the examples so far are actually "**naive**" objects that don't have timezone information. This is fine for simple scripts you use personally, but when creating a web service accessed by users worldwide, timezones are an unavoidable issue.
For example, "July 11, 9:00 AM" in Japan and "July 11, 9:00 AM" in the United States are completely different moments in time. To handle this difference correctly, you need to use "**aware**" objects that have timezone information.
Since Python 3.9, you can easily handle timezones using the standard library's `zoneinfo` module.
import datetime
from zoneinfo import ZoneInfo
# Get the current time with a specified timezone
tokyo_tz = ZoneInfo("Asia/Tokyo")
now_tokyo = datetime.datetime.now(tokyo_tz)
print(f"Current time in Tokyo: {now_tokyo}")
newyork_tz = ZoneInfo("America/New_York")
now_newyork = datetime.datetime.now(newyork_tz)
print(f"Current time in New York: {now_newyork}")
# You can see the timezone information is attached
# Example output:
# Current time in Tokyo: 2025-07-11 07:42:15.123456+09:00
# Current time in New York: 2025-07-10 18:42:15.123456-04:00
When developing international services, always be sure to implement with timezones in mind!
[Practice] Copy, Paste, and Run! Display the Current Time on a Web Page
Finally, using what you've learned, here is a complete HTML example that you can copy and paste to display the current Japan Standard Time (JST) in real-time on a web page. If you save this code as an HTML file, it will work just by opening it in your browser.
※This sample includes JavaScript within the HTML to update the time in real-time.
Save the following code as a file named `clock.html` and open it in your browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Real-time Clock Display</title>
<style>
body {
background-color: #202124;
color: #e8eaed;
font-family: sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
flex-direction: column;
}
h1 {
color: #669df6;
}
#clock {
font-size: 3rem;
font-weight: bold;
background-color: #3c4043;
padding: 20px 40px;
border-radius: 10px;
}
</style>
</head>
<body>
<h1>Current Time in Japan</h1>
<div id="clock">--:--:--</div>
<script>
function updateClock() {
// Generate the time in Japan Standard Time (JST, UTC+9)
const now = new Date();
const jstOffset = 9 * 60; // JST is UTC+9 hours
const localOffset = -now.getTimezoneOffset(); // Local timezone offset in minutes
const jstNow = new Date(now.getTime() + (jstOffset - localOffset) * 60 * 1000);
const hours = String(jstNow.getHours()).padStart(2, '0');
const minutes = String(jstNow.getMinutes()).padStart(2, '0');
const seconds = String(jstNow.getSeconds()).padStart(2, '0');
document.getElementById('clock').textContent = `${hours}:${minutes}:${seconds}`;
}
// Update the clock every second
setInterval(updateClock, 1000);
// Run for the first time on page load
updateClock();
</script>
</body>
</html>
Summary
In this article, we learned how to handle dates and times using Python's `datetime` module.
- Get Current Time: `datetime.now()` and `date.today()`
- Format Conversion: Convert to a string with `strftime()` and to a `datetime` object with `strptime()`
- Date/Time Calculation: Freely add and subtract with `timedelta`
- Timezones: For international apps, it's crucial to use "aware" objects with `zoneinfo`
Once you master the `datetime` module, the range of things you can create expands greatly, including log timestamps, user registration dates, and event countdowns. Feel free to play around with the code in this article and try creating your own programs!
Next Steps
Now that you're comfortable with handling dates and times, why not try tackling file and directory operations? The following article explains how to read and write files and create/delete folders with Python.
Master File and Directory Operations with the os Module »