Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas Dates and Times

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"

)

print

(

"By day:"

)

print

(

dates

)

print

(

)

By month

dates_month

=

pd.

date_range

(

"2024-01-01"

,

periods

=

12

,

freq

=

"M"

)

print

(

"By month:"

)

print

(

dates_month

)

print

(

)

By hour

dates_hour

=

pd.

date_range

(

"2024-01-01 00:00"

,

periods

=

24

,

freq

=

"H"

)

print

(

"By hour (first 5):"

)

print

(

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"

)

]

)

print

(

"DatetimeIndex:"

)

print

(

dt

)

print

(

)

Create a Series with times

s

=

pd.

Series

(

   

[

100

,

200

,

300

]

,

    index

=

pd.

date_range

(

"2024-01-01"

,

periods

=

3

,

freq

=

"D"

)

)

print

(

"Series with a date index:"

)

print

(

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

)

print

(

"Automatically inferred format:"

)

print

(

dt

)

print

(

)

Specify the format

dt2

=

pd.

to_datetime

(

dates_str

,

format

=

"%Y-%m-%d"

)

print

(

"Specified format:"

)

print

(

dt2

)

print

(

)

Handle invalid values

dt3

=

pd.

to_datetime

(

[

"2024-01-01"

,

"invalid"

,

"2024-01-03"

]

,

errors

=

"coerce"

)

print

(

"Handling invalid values (converted to NaT):"

)

print

(

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"

]

)

print

(

"Convert after reading:"

)

print

(

df.

dtypes

)

print

(

)

Method 2: Parse directly when reading

df2

=

pd.

read_csv

(

StringIO

(

csv_data

)

,

parse_dates

=

[

"date"

]

)

print

(

"Parse when reading:"

)

print

(

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"

)

)

print

(

"Date Series:"

)

print

(

s

)

print

(

)

Extract year/month/day

print

(

"Extract year:"

)

print

(

s.

dt

.

year

)

print

(

)

print

(

"Extract month:"

)

print

(

s.

dt

.

month

)

print

(

)

print

(

"Extract day:"

)

print

(

s.

dt

.

day

)

print

(

)

Extract the day of the week (0=Monday, 6=Sunday)

print

(

"Day of the week (number):"

)

print

(

s.

dt

.

dayofweek

)

print

(

)

Extract the day-of-week name

print

(

"Day-of-week name:"

)

print

(

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"

)

print

(

f

"Base date: {date}"

)

print

(

)

Add or subtract days

print

(

f

"+3 days: {date + pd.Timedelta(days=3)}"

)

print

(

f

"-5 days: {date - pd.Timedelta(days=5)}"

)

print

(

)

Date difference

date1

=

pd.

Timestamp

(

"2024-01-01"

)

date2

=

pd.

Timestamp

(

"2024-01-15"

)

print

(

f

"Date difference: {date2 - date1}"

)

print

(

f

"Difference in days: {(date2 - date1).days}"

)

print

(

)

Date Series operations

dates

=

pd.

date_range

(

"2024-01-01"

,

periods

=

5

,

freq

=

"D"

)

print

(

"Date + 3 days:"

)

print

(

dates + pd.

Timedelta

(

days

=

3

)

)

Date offsets

Example

import

pandas

as

pd

date

=

pd.

Timestamp

(

"2024-01-15"

)

print

(

f

"Base date: {date}"

)

print

(

)

Start/end of month

print

(

f

"Start of month: {date + pd.offsets.MonthBegin(1)}"

)

print

(

f

"End of month: {date + pd.offsets.MonthEnd(1)}"

)

print

(

)

Year offset

print

(

f

"+1 year: {date + pd.DateOffset(years=1)}"

)

print

(

f

"-1 month: {date + pd.DateOffset(months=-1)}"

)

print

(

)

Business days

print

(

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"

)

print

(

"Without timezone:"

)

print

(

dates

)

print

(

)

Set Time Zone

dates_utc

=

dates.

tz_localize

(

"UTC"

)

print

(

"UTC timezone set:"

)

print

(

dates_utc

)

print

(

)

Convert timezone

dates_shanghai

=

dates_utc.

tz_convert

(

"Asia/Shanghai"

)

print

(

"Converted to Shanghai timezone:"

)

print

(

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"

]

)

print

(

"Sales data:"

)

print

(

df.

head

(

10

)

)

print

(

)

Statistics by day of the week

print

(

"Average sales by day of the week:"

)

weekday_sales

=

df.

groupby

(

df

[

"date"

]

.

dt

.

day_name

(

)

)

[

"Sales"

]

.

mean

(

)

print

(

weekday_sales

)

print

(

)

Statistics by month

print

(

"Statistics by month:"

)

df

[

"Month"

]

=

df

[

"date"

]

.

dt

.

to_period

(

"M"

)

monthly_sales

=

df.

groupby

(

"Month"

)

[

"Sales"

]

.

sum

(

)

print

(

monthly_sales

)

print

(

)

Calculate the 7-day rolling average

df

[

"7-day rolling average"

]

=

df

[

"Sales"

]

.

rolling

(

window

=

7

)

.

mean

(

)

print

(

"7-day rolling average added:"

)

print

(

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.