Pandas Dates and Times
Pandas provides powerful date and time processing capabilities, making it easy to convert strings to date types and perform various date-related calculations and analyses.
Creating dates and times
The date_range function
Example
import
pandas
as
pd
Create a date range
dates
=
pd.
date_range
(
"2024-01-01"
,
periods
=
10
,
freq
=
"D"
)
(
"By day:"
)
(
dates
)
(
)
By month
dates_month
=
pd.
date_range
(
"2024-01-01"
,
periods
=
12
,
freq
=
"M"
)
(
"By month:"
)
(
dates_month
)
(
)
By hour
dates_hour
=
pd.
date_range
(
"2024-01-01 00:00"
,
periods
=
24
,
freq
=
"H"
)
(
"By hour (first 5):"
)
(
dates_hour
[
:
5
]
)
DatetimeIndex and DatetimeArray
Example
import
pandas
as
pd
import
numpy
as
np
Create using datetime objects
dt
=
pd.
DatetimeIndex
(
[
pd.
Timestamp
(
"2024-01-01"
)
,
pd.
Timestamp
(
"2024-01-02"
)
,
pd.
Timestamp
(
"2024-01-03"
)
]
)
(
"DatetimeIndex:"
)
(
dt
)
(
)
Create a Series with times
s
=
pd.
Series
(
[
100
,
200
,
300
]
,
index
=
pd.
date_range
(
"2024-01-01"
,
periods
=
3
,
freq
=
"D"
)
)
(
"Series with a date index:"
)
(
s
)
Convert strings to dates
pd.to_datetime
Example
import
pandas
as
pd
Convert strings of various formats to dates
dates_str
=
[
"2024-01-01"
,
"2024/01/02"
,
"01-03-2024"
,
"20240104"
]
Automatically infer the format
dt
=
pd.
to_datetime
(
dates_str
)
(
"Automatically inferred format:"
)
(
dt
)
(
)
Specify the format
dt2
=
pd.
to_datetime
(
dates_str
,
format
=
"%Y-%m-%d"
)
(
"Specified format:"
)
(
dt2
)
(
)
Handle invalid values
dt3
=
pd.
to_datetime
(
[
"2024-01-01"
,
"invalid"
,
"2024-01-03"
]
,
errors
=
"coerce"
)
(
"Handling invalid values (converted to NaT):"
)
(
dt3
)
read_csv automatically parses dates
Example
import
pandas
as
pd
from
io
import
StringIO
Simulate CSV data
csv_data
=
"""Date,Sales
2024-01-01,100
2024-01-02,200
2024-01-03,150
"""
Method 1: Convert after reading
df
=
pd.
read_csv
(
StringIO
(
csv_data
)
)
df
[
"date"
]
=
pd.
to_datetime
(
df
[
"date"
]
)
(
"Convert after reading:"
)
(
df.
dtypes
)
(
)
Method 2: Parse directly when reading
df2
=
pd.
read_csv
(
StringIO
(
csv_data
)
,
parse_dates
=
[
"date"
]
)
(
"Parse when reading:"
)
(
df2.
dtypes
)
Accessing date attributes
After a datetime is converted to the datetime type, you can easily extract various attributes.
Example
import
pandas
as
pd
Create a date Series
s
=
pd.
Series
(
pd.
date_range
(
"2024-01-15"
,
periods
=
5
,
freq
=
"D"
)
)
(
"Date Series:"
)
(
s
)
(
)
Extract year/month/day
(
"Extract year:"
)
(
s.
dt
.
year
)
(
)
(
"Extract month:"
)
(
s.
dt
.
month
)
(
)
(
"Extract day:"
)
(
s.
dt
.
day
)
(
)
Extract the day of the week (0=Monday, 6=Sunday)
(
"Day of the week (number):"
)
(
s.
dt
.
dayofweek
)
(
)
Extract the day-of-week name
(
"Day-of-week name:"
)
(
s.
dt
.
day_name
(
)
)
More date attributes
| property | Description | Example |
|---|---|---|
year |
Year | 2024 |
month |
Month (1-12) | 1 |
day |
Day (1-31) | 15 |
hour |
Hour (0-23) | 10 |
minute |
Minute (0-59) | 30 |
dayofweek |
Weekday (0-6) | 0 |
quarter |
Quarter (1-4) | 1 |
is_month_start |
Whether it is the start of the month | True/False |
is_month_end |
Whether it is the end of the month | True/False |
Date arithmetic
Date addition and subtraction
Example
import
pandas
as
pd
Create a date
date
=
pd.
Timestamp
(
"2024-01-15"
)
(
f
"Base date: {date}"
)
(
)
Add or subtract days
(
f
"+3 days: {date + pd.Timedelta(days=3)}"
)
(
f
"-5 days: {date - pd.Timedelta(days=5)}"
)
(
)
Date difference
date1
=
pd.
Timestamp
(
"2024-01-01"
)
date2
=
pd.
Timestamp
(
"2024-01-15"
)
(
f
"Date difference: {date2 - date1}"
)
(
f
"Difference in days: {(date2 - date1).days}"
)
(
)
Date Series operations
dates
=
pd.
date_range
(
"2024-01-01"
,
periods
=
5
,
freq
=
"D"
)
(
"Date + 3 days:"
)
(
dates + pd.
Timedelta
(
days
=
3
)
)
Date offsets
Example
import
pandas
as
pd
date
=
pd.
Timestamp
(
"2024-01-15"
)
(
f
"Base date: {date}"
)
(
)
Start/end of month
(
f
"Start of month: {date + pd.offsets.MonthBegin(1)}"
)
(
f
"End of month: {date + pd.offsets.MonthEnd(1)}"
)
(
)
Year offset
(
f
"+1 year: {date + pd.DateOffset(years=1)}"
)
(
f
"-1 month: {date + pd.DateOffset(months=-1)}"
)
(
)
Business days
(
f
"Next Monday: {date + pd.offsets.Week(weekday=0)}"
)
Timezone handling
Example
import
pandas
as
pd
Create a time without a timezone
dates
=
pd.
date_range
(
"2024-01-01 10:00"
,
periods
=
3
,
freq
=
"H"
)
(
"Without timezone:"
)
(
dates
)
(
)
Set Time Zone
dates_utc
=
dates.
tz_localize
(
"UTC"
)
(
"UTC timezone set:"
)
(
dates_utc
)
(
)
Convert timezone
dates_shanghai
=
dates_utc.
tz_convert
(
"Asia/Shanghai"
)
(
"Converted to Shanghai timezone:"
)
(
dates_shanghai
)
Practical example: Sales data analysis
Example
import
pandas
as
pd
Simulate sales data
df
=
pd.
DataFrame
(
{
"date"
: pd.
date_range
(
"2024-01-01"
,
periods
=
30
,
freq
=
"D"
)
,
"Sales"
:
[
100
,
150
,
120
,
180
,
200
,
90
,
80
]
4
[
100
,
100
]
}
)
df
[
"date"
]
=
pd.
to_datetime
(
df
[
"date"
]
)
(
"Sales data:"
)
(
df.
head
(
10
)
)
(
)
Statistics by day of the week
(
"Average sales by day of the week:"
)
weekday_sales
=
df.
groupby
(
df
[
"date"
]
.
dt
.
day_name
(
)
)
[
"Sales"
]
.
mean
(
)
(
weekday_sales
)
(
)
Statistics by month
(
"Statistics by month:"
)
df
[
"Month"
]
=
df
[
"date"
]
.
dt
.
to_period
(
"M"
)
monthly_sales
=
df.
groupby
(
"Month"
)
[
"Sales"
]
.
sum
(
)
(
monthly_sales
)
(
)
Calculate the 7-day rolling average
df
[
"7-day rolling average"
]
=
df
[
"Sales"
]
.
rolling
(
window
=
7
)
.
mean
(
)
(
"7-day rolling average added:"
)
(
df.
head
(
10
)
)
Common questions
1. Inconsistent date formats
Use pd.to_datetime In this case, you can specify the format parameter to clarify the format and avoid parsing errors.
2. Time zone confusion
When processing data across time zones, ensure that all times use a unified time zone or UTC.
3. Use Timedelta for date arithmetic
For date addition and subtraction, use pd.Timedelta, rather than simple integer addition and subtraction.
When working with time series data, it is recommended to convert date strings to the datetime type as early as possible, so as to take advantage of Pandas' powerful date features.