
Python datetime is a module in the Python standard library, specifically designed for working with dates, times, and the combination of both. The module provides various classes, methods, and functions to perform operations like parsing, formatting, arithmetic, and comparison on date and time objects. The datetime module is part of Python’s built-in library, so you don’t need to install any external packages to use it.
- What is datetime Class?
- How To Create datetime Objects
- What is timedelta Class?
- How To Perform Arithmetic with datetime Objects
- Examples of Formatting and Parsing Dates and Times
- What is timezone Class?
- How To Work with Timezones and UTC
- What is date Class?
- How To Manipulate Dates Using date Class
- What is time Class?
- How To Use time Class for Time Manipulation
- How To Compare and Sort datetime Objects
- Examples of Real-World datetime Applications
The datetime module contains several classes, including:
datetime
: This class represents a single point in time, including the date (year, month, and day) and time (hour, minute, second, and microsecond). It is the most commonly used class for handling date and time data.date
: This class represents a date (year, month, and day) without any time information. It is useful for situations where you only need to work with dates.time
: This class represents a time of day (hour, minute, second, and microsecond) without any date information. It is useful for situations where you only need to work with time.timedelta
: This class represents the duration or difference between two dates or times. It is used for arithmetic operations involving dates and times, such as adding or subtracting days, hours, or minutes.timezone
: This class represents a specific timezone, allowing you to work with dates and times in different time zones and perform timezone conversions.
By understanding and utilizing the classes provided by the Python datetime module, you can efficiently manipulate, analyze, and process date and time data in your Python applications.
What is datetime Class?
The datetime
class is a central component of the Python datetime
module, designed to represent a single point in time that includes both date (year, month, and day) and time (hour, minute, second, and microsecond) information. This class provides methods and attributes for various operations, such as parsing, formatting, arithmetic, and comparison, making it one of the most commonly used classes for handling date and time data in Python.
Key attributes and methods of the datetime
class include:
- Attributes:
year
: Represents the year component of the datetime object.month
: Represents the month component of the datetime object.day
: Represents the day component of the datetime object.hour
: Represents the hour component of the datetime object.minute
: Represents the minute component of the datetime object.second
: Represents the second component of the datetime object.microsecond
: Represents the microsecond component of the datetime object.
- Methods:
today()
: Returns the current local date and time.now()
: Returns the current local date and time with an optional timezone.fromtimestamp()
: Creates a datetime object from a Unix timestamp.strptime()
: Parses a string representing a date and time, according to a given format.strftime()
: Returns a formatted string representing the datetime object, based on a specified format.replace()
: Returns a new datetime object with specified fields replaced by new values.astimezone()
: Returns a new datetime object with the time converted to a specified timezone.timestamp()
: Returns the Unix timestamp for the datetime object.date()
: Returns the date portion (year, month, and day) of the datetime object as adate
object.time()
: Returns the time portion (hour, minute, second, and microsecond) of the datetime object as atime
object.
To create a datetime
object, you can either use the datetime
constructor with the following syntax:
from datetime import datetime
dt = datetime(year, month, day, hour, minute, second, microsecond)
Or use one of the class methods like today()
, now()
, or fromtimestamp()
.
By leveraging the datetime
class, you can efficiently work with date and time information in your Python applications, enabling you to perform complex operations and manipulations with ease.
How To Create datetime Objects
Creating datetime
objects in Python is simple and can be done in several ways, depending on your requirements. Here, we’ll explore some of the most common methods for creating datetime
objects:
- Using the datetime constructor: You can create a
datetime
object by providing the date and time values as arguments to thedatetime
constructor:
from datetime import datetime
dt = datetime(2023, 3, 25, 12, 30, 45) # Year, Month, Day, Hour, Minute, Second
print(dt) # Output: 2023-03-25 12:30:45
- Using the
today()
method: This method returns the current local date and time as adatetime
object:
from datetime import datetime
dt = datetime.today()
print(dt) # Output: Current date and time, e.g., 2023-03-25 12:30:45
- Using the
now()
method: This method returns the current local date and time as adatetime
object, with an optional timezone:
from datetime import datetime
dt = datetime.now()
print(dt) # Output: Current date and time, e.g., 2023-03-25 12:30:45
- Using the
fromtimestamp()
method: This method creates adatetime
object from a Unix timestamp (the number of seconds since January 1, 1970, 00:00:00 UTC):
from datetime import datetime
timestamp = 1672019445
dt = datetime.fromtimestamp(timestamp)
print(dt) # Output: Corresponding date and time, e.g., 2023-03-25 12:30:45
- Using the
strptime()
method: This method parses a string representing a date and time, according to a given format, and returns adatetime
object:
from datetime import datetime
date_string = "2023-03-25 12:30:45"
format_string = "%Y-%m-%d %H:%M:%S"
dt = datetime.strptime(date_string, format_string)
print(dt) # Output: 2023-03-25 12:30:45
These are some of the primary ways to create datetime
objects in Python. Once you have a datetime
object, you can utilize the various methods and attributes provided by the datetime
class to manipulate and work with date and time data.
What is timedelta Class?
The timedelta
class is part of the Python datetime
module and represents a duration or difference between two dates or times. The timedelta
class is particularly useful for performing arithmetic operations involving dates and times, such as adding or subtracting days, hours, minutes, seconds, or even microseconds.
A timedelta
object holds the duration as a combination of days, seconds, and microseconds, and it can handle both positive and negative values.
Here are the main attributes of the timedelta
class:
days
: The number of days in the duration (can be positive or negative).seconds
: The number of seconds in the duration (range: 0 to 86399).microseconds
: The number of microseconds in the duration (range: 0 to 999999).
To create a timedelta
object, you can use the timedelta
constructor with the following syntax:
from datetime import timedelta
duration = timedelta(days, hours, minutes, seconds, microseconds)
You can also create a timedelta
object by calculating the difference between two datetime
objects:
from datetime import datetime, timedelta
dt1 = datetime(2023, 3, 25, 12, 30, 45)
dt2 = datetime(2023, 4, 1, 15, 45, 30)
duration = dt2 - dt1
print(duration) # Output: 7 days, 3:14:45
Some common operations involving timedelta
objects include:
- Adding a duration to a datetime object: To add a specific duration (e.g., 5 days) to a
datetime
object, you can simply use the+
operator:
from datetime import datetime, timedelta
dt = datetime(2023, 3, 25, 12, 30, 45)
duration = timedelta(days=5)
new_dt = dt + duration
print(new_dt) # Output: 2023-03-30 12:30:45
- Subtracting a duration from a datetime object: To subtract a specific duration (e.g., 3 hours) from a
datetime
object, you can use the-
operator:
from datetime import datetime, timedelta
dt = datetime(2023, 3, 25, 12, 30, 45)
duration = timedelta(hours=3)
new_dt = dt - duration
print(new_dt) # Output: 2023-03-25 09:30:45
The timedelta
class is essential when working with date and time manipulations in Python, as it allows you to perform arithmetic operations and handle durations effectively.
How To Perform Arithmetic with datetime Objects
Performing arithmetic operations with datetime
objects is essential when working with date and time data in Python. To do this, you can use the timedelta
class, which represents the duration or difference between two dates or times. Here are some common arithmetic operations you can perform with datetime
objects:
- Addition: To add a specific duration to a
datetime
object, use the+
operator along with atimedelta
object:
from datetime import datetime, timedelta
dt = datetime(2023, 3, 25, 12, 30, 45)
duration = timedelta(days=5, hours=3)
new_dt = dt + duration
print(new_dt) # Output: 2023-03-30 15:30:45
- Subtraction: To subtract a specific duration from a
datetime
object, use the-
operator along with atimedelta
object:
from datetime import datetime, timedelta
dt = datetime(2023, 3, 25, 12, 30, 45)
duration = timedelta(days=3, hours=2)
new_dt = dt - duration
print(new_dt) # Output: 2023-03-22 10:30:45
- Difference: To calculate the difference between two
datetime
objects, use the-
operator. This will return atimedelta
object representing the duration between the two dates:
from datetime import datetime
dt1 = datetime(2023, 3, 25, 12, 30, 45)
dt2 = datetime(2023, 4, 1, 15, 45, 30)
duration = dt2 - dt1
print(duration) # Output: 7 days, 3:14:45
- Comparison: You can compare two
datetime
objects using comparison operators like>
,<
,>=
,<=
,==
, and!=
. This can be useful for sorting or filtering dates:
from datetime import datetime
dt1 = datetime(2023, 3, 25, 12, 30, 45)
dt2 = datetime(2023, 4, 1, 15, 45, 30)
print(dt1 < dt2) # Output: True
print(dt1 == dt2) # Output: False
print(dt1 != dt2) # Output: True
By using the timedelta
class and arithmetic operators, you can easily perform arithmetic operations and comparisons with datetime
objects. This flexibility allows you to manipulate and analyze date and time data effectively in your Python applications.
Examples of Formatting and Parsing Dates and Times
The Python datetime
module provides functionality for formatting and parsing dates and times using the strftime
(string format time) and strptime
(string parse time) methods. These methods use format codes to represent various components of dates and times, such as year, month, day, hour, minute, and second.
Formatting Dates and Times
The strftime
method allows you to format datetime
objects as strings based on a specified format. Here are some examples:
from datetime import datetime
dt = datetime(2023, 3, 25, 12, 30, 45)
# Format as "YYYY-MM-DD"
formatted_date = dt.strftime("%Y-%m-%d")
print(formatted_date) # Output: 2023-03-25
# Format as "DD/MM/YYYY"
formatted_date = dt.strftime("%d/%m/%Y")
print(formatted_date) # Output: 25/03/2023
# Format as "HH:MM:SS"
formatted_time = dt.strftime("%H:%M:%S")
print(formatted_time) # Output: 12:30:45
# Format as "Month Day, Year, HH:MM AM/PM"
formatted_datetime = dt.strftime("%B %d, %Y, %I:%M %p")
print(formatted_datetime) # Output: March 25, 2023, 12:30 PM
Parsing Dates and Times
The strptime
method allows you to parse strings representing dates and times into datetime
objects, based on a specified format. Here are some examples:
from datetime import datetime
# Parse "YYYY-MM-DD" format
date_string = "2023-03-25"
format_string = "%Y-%m-%d"
dt = datetime.strptime(date_string, format_string)
print(dt) # Output: 2023-03-25 00:00:00
# Parse "DD/MM/YYYY" format
date_string = "25/03/2023"
format_string = "%d/%m/%Y"
dt = datetime.strptime(date_string, format_string)
print(dt) # Output: 2023-03-25 00:00:00
# Parse "HH:MM:SS" format
time_string = "12:30:45"
format_string = "%H:%M:%S"
dt = datetime.strptime(time_string, format_string)
print(dt) # Output: 1900-01-01 12:30:45 (Note: Date defaults to Jan 1, 1900)
# Parse "Month Day, Year, HH:MM AM/PM" format
datetime_string = "March 25, 2023, 12:30 PM"
format_string = "%B %d, %Y, %I:%M %p"
dt = datetime.strptime(datetime_string, format_string)
print(dt) # Output: 2023-03-25 12:30:00
By using the strftime
and strptime
methods along with appropriate format codes, you can easily format and parse dates and times in your Python applications, making it simple to work with various date and time representations.
What is timezone Class?
The timezone
class is part of the Python datetime
module and represents a fixed offset from the Coordinated Universal Time (UTC). This class is useful when you need to work with dates and times across different time zones or need to convert between local time and UTC.
The timezone
class has one main attribute:
offset
: Atimedelta
object representing the fixed offset from UTC. The offset can be positive or negative and should be limited to a range of -24 hours to +24 hours.
To create a timezone
object, you can use the timezone
constructor with the following syntax:
from datetime import timezone, timedelta
offset = timedelta(hours=2) # Create a timedelta object representing a 2-hour offset
tz = timezone(offset) # Create a timezone object with the specified offset
You can also use the built-in timezone
instances:
timezone.utc
: Represents the UTC time zone (zero offset).
Here are some examples of using the timezone
class to work with dates and times in different time zones:
- Create a datetime object with a specific time zone:
from datetime import datetime, timezone, timedelta
offset = timedelta(hours=2)
tz = timezone(offset)
dt = datetime(2023, 3, 25, 12, 30, 45, tzinfo=tz)
print(dt) # Output: 2023-03-25 12:30:45+02:00
- Convert a naive (timezone-unaware) datetime object to a timezone-aware datetime object:
from datetime import datetime, timezone
naive_dt = datetime(2023, 3, 25, 12, 30, 45)
aware_dt = naive_dt.replace(tzinfo=timezone.utc)
print(aware_dt) # Output: 2023-03-25 12:30:45+00:00
- Convert a datetime object to a different time zone:
from datetime import datetime, timezone, timedelta
dt_utc = datetime(2023, 3, 25, 12, 30, 45, tzinfo=timezone.utc)
offset = timedelta(hours=-7)
tz_pacific = timezone(offset)
dt_pacific = dt_utc.astimezone(tz_pacific)
print(dt_pacific) # Output: 2023-03-25 05:30:45-07:00
The timezone
class is essential when working with date and time data across different time zones in Python, as it allows you to represent, manipulate, and convert dates and times with time zone information effectively.
How To Work with Timezones and UTC
Working with timezones and UTC in Python is essential when dealing with date and time data from different geographical locations. The datetime
module provides the timezone
class and several useful methods to handle timezone conversions and UTC.
Here’s a guide on how to work with timezones and UTC using the datetime
module:
1. Creating timezone-aware datetime objects
To create a timezone-aware datetime
object, you need to provide the tzinfo
parameter when constructing the datetime
object:
from datetime import datetime, timezone, timedelta
offset = timedelta(hours=-5)
tz = timezone(offset)
dt = datetime(2023, 3, 25, 12, 30, 45, tzinfo=tz)
print(dt) # Output: 2023-03-25 12:30:45-05:00
2. Converting naive datetime objects to timezone-aware datetime objects
If you have a naive (timezone-unaware) datetime
object, you can convert it to a timezone-aware datetime
object using the replace()
method:
from datetime import datetime, timezone
naive_dt = datetime(2023, 3, 25, 12, 30, 45)
aware_dt = naive_dt.replace(tzinfo=timezone.utc)
print(aware_dt) # Output: 2023-03-25 12:30:45+00:00
3. Converting between timezones
To convert a timezone-aware datetime
object to a different timezone, you can use the astimezone()
method:
from datetime import datetime, timezone, timedelta
dt_utc = datetime(2023, 3, 25, 12, 30, 45, tzinfo=timezone.utc)
offset = timedelta(hours=-7)
tz_pacific = timezone(offset)
dt_pacific = dt_utc.astimezone(tz_pacific)
print(dt_pacific) # Output: 2023-03-25 05:30:45-07:00
4. Getting the current time in UTC
To get the current time in UTC, you can use the now()
method with the timezone.utc
parameter:
from datetime import datetime, timezone
current_utc_time = datetime.now(timezone.utc)
print(current_utc_time) # Output: Current date and time in UTC
5. Converting local time to UTC
To convert a local time to UTC, first, create a timezone-aware datetime
object with the local timezone, and then use the astimezone()
method to convert it to UTC:
from datetime import datetime, timezone, timedelta
local_time = datetime(2023, 3, 25, 12, 30, 45)
# Replace this with the actual offset for the local timezone
local_offset = timedelta(hours=-5)
local_tz = timezone(local_offset)
# Create a timezone-aware datetime object with the local timezone
aware_local_time = local_time.replace(tzinfo=local_tz)
# Convert the local time to UTC
utc_time = aware_local_time.astimezone(timezone.utc)
print(utc_time) # Output: 2023-03-25 17:30:45+00:00
These are some of the fundamental ways to work with timezones and UTC in Python. By using the datetime
module and its provided classes and methods, you can effectively handle and manipulate date and time data across different time zones.
What is date Class?
The date
class is part of the Python datetime
module and represents a date (year, month, and day) without any time information. This class is useful when you need to work with date-only data, such as birthdays or calendar events, without any concern for the time component.
The date
class has several attributes:
year
: An integer representing the year (e.g., 2023).month
: An integer representing the month (1 to 12).day
: An integer representing the day of the month (1 to 31, depending on the month).
To create a date
object, you can use the date
constructor with the following syntax:
from datetime import date
d = date(2023, 3, 25)
print(d) # Output: 2023-03-25
You can also use some built-in methods and attributes provided by the date
class:
today()
: Returns the current local date.weekday()
: Returns the day of the week as an integer (0 for Monday, 1 for Tuesday, …, 6 for Sunday).isoweekday()
: Returns the day of the week as an integer (1 for Monday, 2 for Tuesday, …, 7 for Sunday).isoformat()
: Returns the date as an ISO 8601 formatted string (e.g., “2023-03-25”).strftime(format)
: Returns a formatted string representing the date, based on the specified format.
Here’s an example of using the date
class to work with dates:
from datetime import date
# Create a date object
d = date(2023, 3, 25)
# Get the current date
today = date.today()
print(today) # Output: Current date (e.g., 2023-03-25)
# Get the day of the week
weekday = d.weekday()
print(weekday) # Output: 5 (Saturday)
# Format the date as a string
formatted_date = d.strftime("%A, %B %d, %Y")
print(formatted_date) # Output: Saturday, March 25, 2023
The date
class is a useful tool when working with date-only data in Python, allowing you to represent, manipulate, and format dates without considering the time component.
How To Manipulate Dates Using date Class
The date
class in Python’s datetime
module allows you to represent, manipulate, and format dates without any time component. Here are some common ways to manipulate dates using the date
class:
1. Creating a date object
To create a date
object, use the date
constructor with the year, month, and day as arguments:
from datetime import date
d = date(2023, 3, 25)
print(d) # Output: 2023-03-25
2. Getting the current date
To get the current local date, use the today()
method:
from datetime import date
today = date.today()
print(today) # Output: Current date (e.g., 2023-03-25)
3. Extracting year, month, and day from a date object
You can access the year
, month
, and day
attributes of a date
object directly:
from datetime import date
d = date(2023, 3, 25)
print(d.year) # Output: 2023
print(d.month) # Output: 3
print(d.day) # Output: 25
4. Adding or subtracting days, months, or years
To add or subtract days, months, or years from a date, use the timedelta
class:
from datetime import date, timedelta
d = date(2023, 3, 25)
# Add 10 days
new_date = d + timedelta(days=10)
print(new_date) # Output: 2023-04-04
# Subtract 5 days
new_date = d - timedelta(days=5)
print(new_date) # Output: 2023-03-20
Note: The timedelta
class does not directly support adding or subtracting months or years. However, you can use alternative libraries like dateutil
to perform these operations easily.
5. Calculating the difference between two dates
To calculate the difference between two dates, subtract one date
object from another:
from datetime import date
d1 = date(2023, 3, 25)
d2 = date(2023, 4, 10)
date_difference = d2 - d1
print(date_difference) # Output: 16 days, 0:00:00
print(date_difference.days) # Output: 16
6. Formatting a date object
To format a date
object as a string, use the strftime()
method with a format string:
from datetime import date
d = date(2023, 3, 25)
formatted_date = d.strftime("%A, %B %d, %Y")
print(formatted_date) # Output: Saturday, March 25, 2023
These are some common ways to manipulate dates using the date
class in Python. By using the date
class, you can work with date-only data effectively and perform various date manipulations and calculations as needed.
What is time Class?
The time
class is part of the Python datetime
module and represents a time of day, independent of any specific date. This class is useful when you need to work with time-only data, such as durations or daily events, without any concern for the date component.
The time
class has several attributes:
hour
: An integer representing the hour (0 to 23).minute
: An integer representing the minute (0 to 59).second
: An integer representing the second (0 to 59).microsecond
: An integer representing the microsecond (0 to 999999).tzinfo
: An optional timezone object representing the timezone. Defaults toNone
.
To create a time
object, you can use the time
constructor with the following syntax:
from datetime import time
t = time(12, 30, 45)
print(t) # Output: 12:30:45
You can also use some built-in methods and attributes provided by the time
class:
isoformat()
: Returns the time as an ISO 8601 formatted string (e.g., “12:30:45”).strftime(format)
: Returns a formatted string representing the time, based on the specified format.replace(hour, minute, second, microsecond, tzinfo)
: Returns a newtime
object with the specified components replaced.
Here’s an example of using the time
class to work with times:
from datetime import time
# Create a time object
t = time(12, 30, 45)
# Format the time as a string
formatted_time = t.strftime("%I:%M %p")
print(formatted_time) # Output: 12:30 PM
The time
class is a useful tool when working with time-only data in Python, allowing you to represent, manipulate, and format times without considering the date component.
How To Use time Class for Time Manipulation
The time
class in Python’s datetime
module allows you to represent, manipulate, and format time-only data without any date component. Here are some common ways to use the time
class for time manipulation:
1. Creating a time object
To create a time
object, use the time
constructor with the hour, minute, and second as arguments:
from datetime import time
t = time(12, 30, 45)
print(t) # Output: 12:30:45
2. Extracting hour, minute, and second from a time object
You can access the hour
, minute
, and second
attributes of a time
object directly:
from datetime import time
t = time(12, 30, 45)
print(t.hour) # Output: 12
print(t.minute) # Output: 30
print(t.second) # Output: 45
3. Replacing time components
To replace the hour, minute, second, or microsecond components of a time
object, use the replace()
method:
from datetime import time
t = time(12, 30, 45)
# Replace the hour and minute
new_time = t.replace(hour=14, minute=15)
print(new_time) # Output: 14:15:45
4. Formatting a time object
To format a time
object as a string, use the strftime()
method with a format string:
from datetime import time
t = time(12, 30, 45)
formatted_time = t.strftime("%I:%M %p")
print(formatted_time) # Output: 12:30 PM
5. Parsing a time string
To parse a time string and create a time
object, use the datetime.strptime()
method from the datetime
class with a format string:
from datetime import datetime
time_string = "12:30:45"
t = datetime.strptime(time_string, "%H:%M:%S").time()
print(t) # Output: 12:30:45
Note: Although the time
class can represent and manipulate times, it does not support arithmetic operations directly. If you need to perform arithmetic with time values, you can use the datetime
class, which includes both date and time components, or use the timedelta
class to represent durations.
These are some common ways to use the time
class for time manipulation in Python. By using the time
class, you can work with time-only data effectively and perform various time manipulations and formatting as needed.
How To Compare and Sort datetime Objects
Comparing and sorting datetime
objects in Python is quite straightforward, as the datetime
class supports native comparison and sorting operations. Here’s how to do it:
1. Comparing datetime objects
You can use standard comparison operators (<
, <=
, >
, >=
, ==
, !=
) to compare datetime
objects directly:
from datetime import datetime
dt1 = datetime(2023, 3, 25, 12, 30, 45)
dt2 = datetime(2023, 4, 10, 10, 20, 30)
# Check if dt1 is earlier than dt2
print(dt1 < dt2) # Output: True
# Check if dt1 is later than or equal to dt2
print(dt1 >= dt2) # Output: False
# Check if dt1 is equal to dt2
print(dt1 == dt2) # Output: False
2. Sorting a list of datetime objects
You can use the built-in sorted()
function or a list’s sort()
method to sort a list of datetime
objects:
from datetime import datetime
dt1 = datetime(2023, 3, 25, 12, 30, 45)
dt2 = datetime(2023, 4, 10, 10, 20, 30)
dt3 = datetime(2023, 1, 15, 9, 0, 0)
dates = [dt1, dt2, dt3]
# Sort the list in ascending order
sorted_dates = sorted(dates)
print(sorted_dates)
# Output: [datetime.datetime(2023, 1, 15, 9, 0), datetime.datetime(2023, 3, 25, 12, 30, 45), datetime.datetime(2023, 4, 10, 10, 20, 30)]
# Sort the list in descending order
sorted_dates_desc = sorted(dates, reverse=True)
print(sorted_dates_desc)
# Output: [datetime.datetime(2023, 4, 10, 10, 20, 30), datetime.datetime(2023, 3, 25, 12, 30, 45), datetime.datetime(2023, 1, 15, 9, 0)]
# Alternatively, use the sort() method of the list
dates.sort()
print(dates)
# Output: [datetime.datetime(2023, 1, 15, 9, 0), datetime.datetime(2023, 3, 25, 12, 30, 45), datetime.datetime(2023, 4, 10, 10, 20, 30)]
Examples of Real-World datetime Applications
Python’s datetime
module is widely used in various real-world applications to handle date and time data. Here are some examples:
1. Task scheduling and reminders
Applications that manage tasks, events, or reminders often require handling and manipulating dates and times to schedule and notify users about upcoming events. The datetime
module can be used to calculate the time left for an event or to determine when to send a reminder.
from datetime import datetime, timedelta
# Event scheduled for 10 days from now
event_date = datetime.now() + timedelta(days=10)
# Set a reminder 2 days before the event
reminder_date = event_date - timedelta(days=2)
print("Event date:", event_date)
print("Reminder date:", reminder_date)
2. Log analysis and time-based data processing
Logs and time-based data often require processing and analysis based on timestamps. The datetime
module can be used to parse, compare, and filter logs or time-series data.
from datetime import datetime
log_entries = [
"2023-03-25 10:15:32 - User logged in",
"2023-03-25 10:16:05 - User viewed profile",
"2023-03-25 10:20:20 - User logged out",
]
# Parse log timestamps and calculate time delta between events
timestamps = [datetime.strptime(entry.split(" - ")[0], "%Y-%m-%d %H:%M:%S") for entry in log_entries]
time_deltas = [timestamps[i + 1] - timestamps[i] for i in range(len(timestamps) - 1)]
print("Time deltas between events:", time_deltas)
3. Date range filtering for reports and analytics
Applications that generate reports or perform analytics often need to filter data based on a specific date range. The datetime
module can be used to define and compare date ranges.
from datetime import datetime, timedelta
# Define a date range for the past week
today = datetime.now()
start_date = today - timedelta(weeks=1)
end_date = today
# Sample data with timestamps
data = [
{"timestamp": datetime(2023, 3, 20, 15, 30), "value": 100},
{"timestamp": datetime(2023, 3, 22, 11, 45), "value": 150},
{"timestamp": datetime(2023, 3, 25, 9, 20), "value": 200},
]
# Filter data within the date range
filtered_data = [entry for entry in data if start_date <= entry["timestamp"] <= end_date]
print("Filtered data:", filtered_data)
4. Age calculation
The datetime
module can be used to calculate a person’s age based on their birthdate.
from datetime import datetime
def calculate_age(birthdate):
today = datetime.now()
age = today.year - birthdate.year - ((today.month, today.day) < (birthdate.month, birthdate.day))
return age
birthdate = datetime(1995, 4, 30)
age = calculate_age(birthdate)
print("Age:", age)
These are just a few examples of real-world applications where Python’s datetime
module is used to handle and manipulate date and time data effectively.