Exploring the Python Datetime Module
The datetime module in Python provides classes for manipulating dates and times. It includes tools for working with time intervals, formatting dates, and performing date arithmetic. In this guide, we'll explore how to work with the datetime module.
Importing the Datetime Module
Before using any of the functions in the datetime module, we need to import it into our Python program. The datetime module is part of Python's standard library, so no extra installation is required.
# To import the datetime module
import datetime
# Now you can use any function from the datetime module, like datetime.datetime.now() or datetime.date.today()
# To import the datetime module
import datetime
# Now you can use any function from the datetime module, like datetime.datetime.now() or datetime.date.today()
Once the datetime module is imported, you can access the various classes and functions it offers, such as datetime.datetime.now() for the current time or datetime.date.today() for today's date.
Datetime Module Functions
The datetime module contains several classes and functions for working with dates and times. Below are some of the most commonly used functions:
datetime.now() | datetime.date() | datetime.today() |
datetime.strptime() | datetime.strftime() | timedelta() |
datetime.fromtimestamp() | datetime.timestamp() |
1. Getting the Current Date and Time with datetime.now()
Python’s built-in datetime module allows you to work with dates and times. To get the current date and time, you can use the now() function from the datetime class.
from datetime import datetime
now = datetime.now()
print("Current date and time:", now)
from datetime import datetime
now = datetime.now()
print("Current date and time:", now)
How It Works:
- from datetime import datetime: This imports the datetime class from the datetime module.
- datetime.now(): This function returns the current local date and time as a datetime object.
- now: A variable that stores the current date and time.
- print(...): This prints a message followed by the value of now. The datetime object is automatically formatted as a readable string.
Output
Current date and time: 2025-06-18 14:45:30.123456
Current date and time: 2025-06-18 14:45:30.123456
2. Creating a Date with datetime.date()
You can create a specific date in Python using the date() function from the datetime module. This is useful when you want to work with or display a fixed date.
from datetime import date
d = date(2025, 6, 18)
print("The date is:", d)
from datetime import date
d = date(2025, 6, 18)
print("The date is:", d)
How It Works:
- from datetime import date: This imports the date class from the datetime module.
- date(2025, 6, 18): Creates a date object representing June 18, 2025. The order is year, month, day.
- d: A variable that stores the created date.
- print(...): Prints a message along with the date value. The date object is automatically formatted as YYYY-MM-DD.
Output
The date is: 2025-06-18
The date is: 2025-06-18
3. Getting Today's Date with datetime.today()
The datetime.today() function returns the current local date and time just like datetime.now(), but it always returns a datetime object representing the current date with the current time.
from datetime import datetime
today = datetime.today()
print("Today's date and time:", today)
from datetime import datetime
today = datetime.today()
print("Today's date and time:", today)
How It Works:
- from datetime import datetime: Imports the datetime class from the datetime module.
- datetime.today(): Returns the current local date and time as a datetime object.
- today: Stores the current date and time.
- print(...): Prints the current date and time.
Output
Today's date and time: 2025-06-18 14:45:30.123456
Today's date and time: 2025-06-18 14:45:30.123456
4. Parsing a Date String with datetime.strptime()
The strptime() function allows you to convert a date and time represented as a string into a datetime object by specifying the format of the input string.
from datetime import datetime
date_string = "2025-06-18 14:30:00"
dt = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print("Parsed datetime object:", dt)
from datetime import datetime
date_string = "2025-06-18 14:30:00"
dt = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print("Parsed datetime object:", dt)
How It Works:
- from datetime import datetime: Imports the datetime class.
- date_string: A string representing a date and time.
- datetime.strptime(...): Parses the string into a datetime object using the provided format string.
- "%Y-%m-%d %H:%M:%S": The format specifies the input string layout:
- %Y: 4-digit year
- %m: 2-digit month
- %d: 2-digit day
- %H: 2-digit hour (24-hour clock)
- %M: 2-digit minute
- %S: 2-digit second
- print(...): Prints the resulting datetime object.
Output
Parsed datetime object: 2025-06-18 14:30:00
Parsed datetime object: 2025-06-18 14:30:00
5. Formatting Date and Time with datetime.strftime()
The strftime() function is used to format a datetime object as a string in a specified format. This is useful when you want to display the date and time in a more readable or custom way.
from datetime import datetime
now = datetime.now()
formatted = now.strftime("%A, %d %B %Y %I:%M %p")
print("Formatted date and time:", formatted)
from datetime import datetime
now = datetime.now()
formatted = now.strftime("%A, %d %B %Y %I:%M %p")
print("Formatted date and time:", formatted)
How It Works:
- datetime.now(): Gets the current date and time.
- strftime(...): Formats the datetime object into a string.
- "%A, %d %B %Y %I:%M %p": Specifies the format:
- %A: Full weekday name
- %d: Day of the month (zero-padded)
- %B: Full month name
- %Y: Four-digit year
- %I: Hour (12-hour clock)
- %M: Minutes
- %p: AM or PM
- print(...): Displays the formatted string.
Output
Formatted date and time: Wednesday, 18 June 2025 02:45 PM
Formatted date and time: Wednesday, 18 June 2025 02:45 PM
6. Calculating Time Differences with datetime.timedelta
The timedelta class represents a duration — the difference between two dates or times. You can use it to add or subtract days, hours, minutes, etc., from a datetime object.
from datetime import datetime, timedelta
today = datetime.today()
future = today + timedelta(days=5)
print("Today:", today)
print("5 days from today:", future)
from datetime import datetime, timedelta
today = datetime.today()
future = today + timedelta(days=5)
print("Today:", today)
print("5 days from today:", future)
How It Works:
- timedelta(days=5): Creates a time difference of 5 days.
- today + timedelta(...): Adds 5 days to today’s date.
- today and future: Store the current date and the future date.
- print(...): Prints both dates.
Output
Today: 2025-06-18 14:45:30.123456
5 days from today: 2025-06-23 14:45:30.123456
Today: 2025-06-18 14:45:30.123456
5 days from today: 2025-06-23 14:45:30.123456
7. Converting a Timestamp to Date and Time with datetime.fromtimestamp()
The fromtimestamp() function converts a Unix timestamp (seconds since January 1, 1970) into a datetime object.
from datetime import datetime
timestamp = 1750249200
dt = datetime.fromtimestamp(timestamp)
print("Date and time from timestamp:", dt)
from datetime import datetime
timestamp = 1750249200
dt = datetime.fromtimestamp(timestamp)
print("Date and time from timestamp:", dt)
How It Works:
- timestamp: A Unix timestamp representing a moment in time.
- datetime.fromtimestamp(...): Converts the timestamp into a datetime object.
- dt: Stores the resulting date and time.
- print(...): Displays the converted datetime.
Output
Date and time from timestamp: 2025-07-18 15:00:00
Date and time from timestamp: 2025-07-18 15:00:00
8. Converting a Date and Time to Timestamp with datetime.timestamp()
The timestamp() function returns the Unix timestamp for a given datetime object — the number of seconds since January 1, 1970 (UTC).
from datetime import datetime
dt = datetime(2025, 7, 18, 15, 0, 0)
ts = dt.timestamp()
print("Unix timestamp:", ts)
from datetime import datetime
dt = datetime(2025, 7, 18, 15, 0, 0)
ts = dt.timestamp()
print("Unix timestamp:", ts)
How It Works:
- datetime(2025, 7, 18, 15, 0, 0): Creates a datetime object for a specific date and time.
- timestamp(): Converts the datetime object into a Unix timestamp (a float).
- ts: Stores the resulting timestamp.
- print(...): Displays the Unix timestamp.
Output
Unix timestamp: 1750249200.0
Unix timestamp: 1750249200.0
What's Next?
Up next: the re module. Regular expressions let you search, match, and manipulate text with precision. Whether you're validating input, extracting data, or cleaning up strings, the re module gives you powerful pattern-matching capabilities. Let's dive in and learn how to use regular expressions effectively in Python.