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:
Function | Description |
---|---|
datetime.now() | Returns the current local date and time as a datetime object. |
datetime.date() | Returns the current local date (year, month, day). |
datetime.today() | Returns the current local date (year, month, day) as a date object. |
datetime.strptime() | Parses a string into a datetime object using a specified format. |
datetime.strftime() | Formats a datetime object into a string according to a specified format. |
timedelta() | Represents the difference between two datetime objects. |
datetime.utcnow() | Returns the current UTC date and time as a datetime object. |
datetime.combine() | Combines a date object and time object into a datetime object. |
datetime.fromtimestamp() | Converts a timestamp (seconds since the Unix epoch) to a datetime object. |
datetime.timestamp() | Returns the timestamp corresponding to a datetime object. |
datetime.fromisoformat() | Parses a string in ISO 8601 format into a datetime object. |
datetime.isoformat() | Returns a string representing a datetime object in ISO 8601 format. |
datetime.now(tz) | Returns the current date and time in the specified time zone tz as a datetime object. |
datetime.replace() | Returns a new datetime object with one or more attributes replaced (e.g., year, month, day). |
datetime.utctimetuple() | Returns a time tuple representing a datetime object in UTC. |
datetime.weekday() | Returns the day of the week as an integer (Monday is 0, Sunday is 6). |
datetime.isoweekday() | Returns the day of the week as an integer (Monday is 1, Sunday is 7). |
datetime.isocalendar() | Returns a tuple containing ISO year, ISO week number, and ISO weekday. |
datetime.timezone() | Returns a timezone object for a fixed offset from UTC. |
datetime.strptime() | Converts a string to a datetime object using a specific format. |
timedelta.total_seconds() | Returns the total number of seconds contained in the timedelta object. |
Examples of Using Datetime Functions
Below are some practical examples of using the datetime module functions.
import datetime
# Example 1: datetime.now()
now = datetime.datetime.now() # Current date and time
print(now) # Output: Current date and time (e.g., 2025-03-16 14:34:45.123456)
# Example 2: datetime.date()
today = datetime.date.today() # Current date
print(today) # Output: Current date (e.g., 2025-03-16)
# Example 3: datetime.strptime() - Parse string to a datetime object
date_str = '2025-03-16 14:34:45'
date_obj = datetime.datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
print(date_obj) # Output: 2025-03-16 14:34:45
# Example 4: datetime.strftime() - Format datetime object to string
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S') # Format datetime as string
print(formatted_date) # Output: 2025-03-16 14:34:45
# Example 5: timedelta() - Calculate difference between two datetime objects
date1 = datetime.datetime(2025, 3, 16, 14, 30)
date2 = datetime.datetime(2025, 3, 17, 14, 30)
delta = date2 - date1 # Time difference
print(delta) # Output: 1 day, 0:00:00
print(delta.total_seconds()) # Output: 86400.0 seconds
# Example 6: datetime.utcnow() - Get current UTC date and time
utc_now = datetime.datetime.utcnow()
print(utc_now) # Output: Current UTC date and time (e.g., 2025-03-16 19:34:45.123456)
# Example 7: datetime.combine() - Combine date and time into datetime
date_part = datetime.date(2025, 3, 16)
time_part = datetime.time(14, 30)
combined_datetime = datetime.datetime.combine(date_part, time_part)
print(combined_datetime) # Output: 2025-03-16 14:30:00
# Example 8: datetime.fromtimestamp() - Convert timestamp to datetime
timestamp = 1678954475 # Example Unix timestamp
dt_from_timestamp = datetime.datetime.fromtimestamp(timestamp)
print(dt_from_timestamp) # Output: 2025-03-16 14:34:35 (depending on the timestamp)
# Example 9: datetime.isoformat() - Return ISO format string for the datetime object
iso_format = now.isoformat() # Convert to ISO format
print(iso_format) # Output: 2025-03-16T14:34:45.123456
# Example 10: datetime.replace() - Replace certain parts of the datetime
new_time = now.replace(hour=9, minute=0)
print(new_time) # Output: 2025-03-16 09:00:00
# Example 11: datetime.weekday() - Get the weekday (0 = Monday, 6 = Sunday)
weekday = now.weekday()
print(weekday) # Output: 6 (Sunday)
# Example 12: datetime.isoweekday() - Get the ISO weekday (1 = Monday, 7 = Sunday)
iso_weekday = now.isoweekday()
print(iso_weekday) # Output: 7 (Sunday)
# Example 13: datetime.isocalendar() - Get the ISO calendar (year, week number, weekday)
iso_calendar = now.isocalendar()
print(iso_calendar) # Output: (2025, 11, 7) (ISO year, week number, weekday)
# Example 14: datetime.timezone() - Create a timezone object
tz = datetime.timezone(datetime.timedelta(hours=3)) # UTC+3
print(tz) # Output: UTC+03:00
# Example 15: datetime.fromisoformat() - Parse ISO 8601 formatted string into datetime object
iso_str = '2025-03-16T14:34:45.123456'
iso_dt = datetime.datetime.fromisoformat(iso_str)
print(iso_dt) # Output: 2025-03-16 14:34:45.123456
# Example 16: datetime.utctimetuple() - Convert datetime object to UTC time tuple
utc_time_tuple = now.utctimetuple()
print(utc_time_tuple) # Output: time.struct_time(tm_year=2025, tm_mon=3, tm_mday=16, tm_hour=14, tm_min=34, tm_sec=45, tm_wday=6, tm_yday=75, tm_isdst=-1)
# Example 17: datetime.timestamp() - Get timestamp from datetime object
timestamp_from_dt = now.timestamp()
print(timestamp_from_dt) # Output: 1678972485.123456 (seconds since epoch)
# Example 18: timedelta.total_seconds() - Get total seconds in a timedelta
time_difference = datetime.timedelta(days=2, hours=3)
print(time_difference.total_seconds()) # Output: 183600.0
import datetime
# Example 1: datetime.now()
now = datetime.datetime.now() # Current date and time
print(now) # Output: Current date and time (e.g., 2025-03-16 14:34:45.123456)
# Example 2: datetime.date()
today = datetime.date.today() # Current date
print(today) # Output: Current date (e.g., 2025-03-16)
# Example 3: datetime.strptime() - Parse string to a datetime object
date_str = '2025-03-16 14:34:45'
date_obj = datetime.datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
print(date_obj) # Output: 2025-03-16 14:34:45
# Example 4: datetime.strftime() - Format datetime object to string
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S') # Format datetime as string
print(formatted_date) # Output: 2025-03-16 14:34:45
# Example 5: timedelta() - Calculate difference between two datetime objects
date1 = datetime.datetime(2025, 3, 16, 14, 30)
date2 = datetime.datetime(2025, 3, 17, 14, 30)
delta = date2 - date1 # Time difference
print(delta) # Output: 1 day, 0:00:00
print(delta.total_seconds()) # Output: 86400.0 seconds
# Example 6: datetime.utcnow() - Get current UTC date and time
utc_now = datetime.datetime.utcnow()
print(utc_now) # Output: Current UTC date and time (e.g., 2025-03-16 19:34:45.123456)
# Example 7: datetime.combine() - Combine date and time into datetime
date_part = datetime.date(2025, 3, 16)
time_part = datetime.time(14, 30)
combined_datetime = datetime.datetime.combine(date_part, time_part)
print(combined_datetime) # Output: 2025-03-16 14:30:00
# Example 8: datetime.fromtimestamp() - Convert timestamp to datetime
timestamp = 1678954475 # Example Unix timestamp
dt_from_timestamp = datetime.datetime.fromtimestamp(timestamp)
print(dt_from_timestamp) # Output: 2025-03-16 14:34:35 (depending on the timestamp)
# Example 9: datetime.isoformat() - Return ISO format string for the datetime object
iso_format = now.isoformat() # Convert to ISO format
print(iso_format) # Output: 2025-03-16T14:34:45.123456
# Example 10: datetime.replace() - Replace certain parts of the datetime
new_time = now.replace(hour=9, minute=0)
print(new_time) # Output: 2025-03-16 09:00:00
# Example 11: datetime.weekday() - Get the weekday (0 = Monday, 6 = Sunday)
weekday = now.weekday()
print(weekday) # Output: 6 (Sunday)
# Example 12: datetime.isoweekday() - Get the ISO weekday (1 = Monday, 7 = Sunday)
iso_weekday = now.isoweekday()
print(iso_weekday) # Output: 7 (Sunday)
# Example 13: datetime.isocalendar() - Get the ISO calendar (year, week number, weekday)
iso_calendar = now.isocalendar()
print(iso_calendar) # Output: (2025, 11, 7) (ISO year, week number, weekday)
# Example 14: datetime.timezone() - Create a timezone object
tz = datetime.timezone(datetime.timedelta(hours=3)) # UTC+3
print(tz) # Output: UTC+03:00
# Example 15: datetime.fromisoformat() - Parse ISO 8601 formatted string into datetime object
iso_str = '2025-03-16T14:34:45.123456'
iso_dt = datetime.datetime.fromisoformat(iso_str)
print(iso_dt) # Output: 2025-03-16 14:34:45.123456
# Example 16: datetime.utctimetuple() - Convert datetime object to UTC time tuple
utc_time_tuple = now.utctimetuple()
print(utc_time_tuple) # Output: time.struct_time(tm_year=2025, tm_mon=3, tm_mday=16, tm_hour=14, tm_min=34, tm_sec=45, tm_wday=6, tm_yday=75, tm_isdst=-1)
# Example 17: datetime.timestamp() - Get timestamp from datetime object
timestamp_from_dt = now.timestamp()
print(timestamp_from_dt) # Output: 1678972485.123456 (seconds since epoch)
# Example 18: timedelta.total_seconds() - Get total seconds in a timedelta
time_difference = datetime.timedelta(days=2, hours=3)
print(time_difference.total_seconds()) # Output: 183600.0
What's Next?
Next, you'll dive into the Python os module, which provides a way to interact with the operating system. You'll learn how to work with files and directories, navigate the file system, and access system-level information. This module is essential for tasks like file manipulation and automation.