Python Learning Notes: Handling Time in Python

In Python,there are mainly two ways to handle time: using the built-in datetime module and using pandas’ Timestamp and time series features. Both have their advantages, summarized and compared below.1.Built-in datetime module The datetime module is part of the Python standard library and provides basic classes for date and time handling, including date, time, datetime, timedelta, and tzinfo.

Common Classes:

  • <span>datetime.date</span>: Handles dates (year, month, day)

  • <span>datetime.time</span>: Handles time (hour, minute, second, microsecond)

  • <span>datetime.datetime</span>: Handles both date and time

  • <span>datetime.timedelta</span>: Represents the difference between two dates or times

  • <span>datetime.tzinfo</span>: Base class for timezone information

from datetime import datetime, date, time, timedelta
# Current time
now = datetime.now()
print(now)   # 2025-11-01 10:30:00.123456
# Create a specific date and time
dt = datetime(2024, 12, 25, 10, 30, 0)
print(dt)  # 2024-12-25 10:30:00
d = dt.date()
print(d)  # Output: 2024-12-25
# Time calculation
tomorrow = dt + timedelta(days=1)
print(tomorrow)  # 2024-12-26 10:30:00
# Formatting
formatted = dt.strftime("%Y-%m-%d %H:%M:%S")
print(formatted)  # "2024-12-25 10:30:00"
# %Y Four-digit year
# %y Two-digit year
# %m Two-digit month [01,12]
# %d Two-digit day [01,31]
# Parsing string
parsed_dt = datetime.strptime("2023-12-25 10:30:00", "%Y-%m-%d %H:%M:%S")
print(parsed_dt)  # 2023-12-25 10:30:00

Usage Principle of .date() Method

.date() is a method of the datetime object in Python, used to extract the date part from the datetime object.

Basic Usage

from datetime import datetime, date
# Create a datetime object
dt = datetime(2023, 12, 25, 14, 30, 45)
print(f"Original datetime: {dt}")  # 2023-12-25 14:30:45
# Use .date() to extract the date part
date_part = dt.date()
print(f"Extracted date: {date_part}")  # 2023-12-25
print(f"Type: {type(date_part)}")  # &lt;class 'datetime.date'&gt;

Working Principle

1. Data Type Conversion

  • Input: <span>datetime.datetime</span> object (contains date and time information)

  • Output: <span>datetime.date</span> object (contains only date information)

  • Process: Discard the time part (hour, minute, second, microsecond), keeping only year, month, and day

from datetime import datetime
dt = datetime(2023, 12, 25, 14, 30, 45, 123456)
print(f"Complete datetime: {dt}")  # 2023-12-25 14:30:45.123456
date_only = dt.date()
print(f"Only date: {date_only}")  # 2023-12-25

In pandas,

<span><span>.date()</span></span> is accessed using the <span><span>.dt</span></span> accessor:

import pandas as pd
from datetime import datetime
# Create a time series
dates = pd.Series([
    datetime(2023, 12, 25, 10, 30),
    datetime(2023, 12, 26, 14, 45),
    datetime(2023, 12, 27, 18, 15)
])
# Extract date part
date_parts = dates.dt.date
print(date_parts)  # 0    2023-12-25
# 1    2023-12-26
# 2    2023-12-27
# dtype: object

Practical Application Scenarios

1. Date Comparison

from datetime import datetime, date
dt1 = datetime(2023, 12, 25, 10, 30)
dt2 = datetime(2023, 12, 25, 18, 45)
# Direct comparison of datetime considers the time part
print(dt1 == dt2)  # False
# Compare only the date part
print(dt1.date() == dt2.date())  # True

2. Grouping Statistics by Date

import pandas as pd
from datetime import datetime
# Simulate sales data
data = {
    'timestamp': [
        datetime(2023, 12, 25, 9, 0),
        datetime(2023, 12, 25, 14, 30),
        datetime(2023, 12, 26, 10, 15),
        datetime(2023, 12, 26, 16, 45)
    ],
    'sales': [100, 150, 200, 180]
}
df = pd.DataFrame(data)
# Add date column
df['date'] = df['timestamp'].dt.date
# Group by date and calculate statistics
daily_sales = df.groupby('date')['sales'].sum()
print(daily_sales)

3. Date Filtering

import pandas as pd
from datetime import datetime, date
# Create data
df = pd.DataFrame({
    'datetime': pd.date_range('2023-12-25', periods=5, freq='12H'),
    'value': range(5)
})
# Filter data for a specific date
target_date = date(2023, 12, 26)
filtered_data = df[df['datetime'].dt.date == target_date]
print(filtered_data)

2. Time Handling in pandas

pandas provides powerful time series processing capabilities, mainly used for data analysis and processing. The main classes include Timestamp, Period, Timedelta, and DatetimeIndex.

Main Features:

  • Handles time series data, supports vectorized operations

  • Supports time range generation, frequency conversion, moving window operations, etc.

  • Timezone handling

  • Seamless integration with DataFrame and Series

Common Classes:

  • <span>pd.Timestamp</span>: Timestamp, equivalent to Python’s datetime but with more features

  • <span>pd.Timedelta</span>: Time interval, equivalent to Python’s timedelta

  • <span>pd.DatetimeIndex</span>: Timestamp index

  • <span>pd.Period</span>: Period (time interval)

  • <span>pd.PeriodIndex</span>: Period index

import pandas as pd
# Create Timestamp
ts = pd.Timestamp('2024-12-25 10:30:00')
print(ts)  # 2024-12-25 10:30:00
# Create time series
dates = pd.date_range('2024-12-25', periods=5, freq='D')
print(dates)  # DatetimeIndex(['2024-12-25', '2024-12-26', '2024-12-27', '2024-12-28', '2024-12-29'], dtype='datetime64[ns]', freq='D')
# Convert to DataFrame index
df = pd.DataFrame({'value': [1, 2, 3, 4, 5]}, index=dates)
print(df)
# Time series operations
df_shifted = df.shift(1)  # Shift one day back
print(df_shifted)
# Resampling
df_resampled = df.resample('2D').mean()  # Resample every 2 days, taking the mean
print(df_resampled)
# Timezone handling
ts_utc = ts.tz_localize('UTC')
print(ts_utc)  # 2023-12-25 10:30:00+00:00
ts_beijing = ts_utc.tz_convert('Asia/Shanghai')
print(ts_beijing)  # 2023-12-25 18:30:00+08:00
# Convert string to time series
date_strings = ['2023-12-25', '2023-12-26', '2023-12-27']
ts_series = pd.to_datetime(date_strings)
print(ts_series)  # DatetimeIndex(['2023-12-25', '2023-12-26', '2023-12-27'], dtype='datetime64[ns]', freq=None)

3. Comparative Summary

Feature datetime Module pandas Time Handling
Applicable Scenarios Simple date and time operations, single date and time handling Handling time series data, data analysis
Performance Suitable for single date and time Vectorized operations, high performance for large data
Functionality Basic date and time operations, formatting, parsing Includes datetime functionality, plus advanced features like resampling, moving windows, timezone conversion, etc.
Timezone Support Requires tzinfo or pytz Built-in timezone support, easy conversion
Integration with Data Structures Used independently Tightly integrated with Series and DataFrame, can be used as an index

Leave a Comment