datetime
The Python datetime
module provides classes and tools for manipulating dates and times in an efficient way. It provides both date and time arithmetic and supports time zones.
Here’s a quick example:
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2025, 6, 20, 16, 31, 34, 273244)
Key Features
- Represents dates and times with precision
- Performs arithmetic on date and time objects
- Supports time zones
- Converts between different date and time formats
Frequently Used Classes and Functions
Object | Type | Description |
---|---|---|
datetime.datetime |
Class | Combines date and time |
datetime.date |
Class | Represents a date (year, month, day) |
datetime.time |
Class | Represents a time independent of any date |
datetime.timedelta |
Class | Represents the difference between two dates/times |
datetime.timezone |
Class | Implements fixed-offset timezone |
datetime.datetime.now() |
Class method | Returns the current local date and time |
Examples
Calculating a date 10 days from now:
>>> from datetime import datetime, timedelta
>>> datetime.now() + timedelta(days=10)
datetime.datetime(2025, 6, 30, 16, 35, 18, 55997)
Formatting a date as a string:
>>> now = datetime.now()
>>> now.strftime("%Y-%m-%d %H:%M:%S")
'2025-06-20 16:36:01'
Common Use Cases
- Calculating the difference between dates and times
- Formatting dates and times
- Scheduling events in specific time zones
- Parsing date and time strings into
datetime
objects
Real-World Example
Suppose you need to schedule a meeting reminder 30 minutes before the meeting time. Here’s how you can do it using the datetime
module:
>>> from datetime import datetime, timedelta
>>> meeting_time = datetime(2025, 6, 19, 15, 0, 0)
>>> reminder_time = meeting_time - timedelta(minutes=30)
>>> reminder_time.strftime("%Y-%m-%d %H:%M:%S")
'2025-06-19 14:30:00'
In this example, you use the datetime
module to calculate the reminder time, ensuring that the meeting notification is sent 30 minutes before.
Related Resources
Tutorial
Using Python datetime to Work With Dates and Times
Have you ever wondered about working with dates and times in Python? In this tutorial, you'll learn all about the built-in Python datetime library. You'll also learn about how to manage time zones and daylight saving time, and how to do accurate arithmetic on dates and times.
For additional information on related topics, take a look at the following resources:
- How to Get and Use the Current Time in Python (Tutorial)
- A Beginner’s Guide to the Python time Module (Tutorial)
- Using Python's datetime Module (Course)
- How to Get the Current Time in Python (Course)
- Mastering Python's Built-in time Module (Course)
By Leodanis Pozo Ramos • Updated June 26, 2025