Dates and Time Series
Dates and times appear in almost every dataset: order times, sensor timestamps, birthdays. pandas has a dedicated datetime64 type with rich support: parsing text, extracting parts like the month or weekday, date arithmetic, filtering by date ranges, and treating data indexed by time as a time series.
Parsing with to_datetime()
import pandas as pd
rides = pd.DataFrame({
"ride": [1, 2, 3, 4],
"start": ["2024-03-29 08:15", "2024-03-30 17:40", "2024-03-31 23:05", "2024-04-01 07:55"],
"end": ["2024-03-29 08:42", "2024-03-30 18:31", "2024-04-01 00:10", "2024-04-01 08:20"],
})
rides["start"] = pd.to_datetime(rides["start"])
rides["end"] = pd.to_datetime(rides["end"])
print(rides.dtypes)
print(rides)ride int64
start datetime64[ns]
end datetime64[ns]
dtype: object
ride start end
0 1 2024-03-29 08:15:00 2024-03-29 08:42:00
1 2 2024-03-30 17:40:00 2024-03-30 18:31:00
2 3 2024-03-31 23:05:00 2024-04-01 00:10:00
3 4 2024-04-01 07:55:00 2024-04-01 08:20:00
For known layouts pass format= (faster and unambiguous), such as pd.to_datetime(s, format="%d.%m.%Y") for "31.03.2024".
The .dt accessor
Just as .str gives string methods, .dt gives date parts for a whole column:
import pandas as pd
starts = pd.Series(pd.to_datetime([
"2024-03-29 08:15", "2024-03-30 17:40", "2024-03-31 23:05", "2024-04-01 07:55",
]))
print(pd.DataFrame({
"date": starts.dt.date,
"year": starts.dt.year,
"month": starts.dt.month,
"day_name": starts.dt.day_name(),
"hour": starts.dt.hour,
"weekend": starts.dt.dayofweek >= 5,
})) date year month day_name hour weekend
0 2024-03-29 2024 3 Friday 8 False
1 2024-03-30 2024 3 Saturday 17 True
2 2024-03-31 2024 3 Sunday 23 True
3 2024-04-01 2024 4 Monday 7 False
dayofweek counts Monday as 0 and Sunday as 6, so >= 5 marks weekends. Other useful ones: .dt.quarter, .dt.isocalendar().week, .dt.month_name(), .dt.strftime("%d/%m") to format as text, and .dt.floor("h") to round down to the hour.
Durations: subtracting dates
Subtracting two datetimes gives a Timedelta (a duration). Its .dt.total_seconds() converts to a number:
import pandas as pd
rides = pd.DataFrame({
"start": pd.to_datetime(["2024-03-29 08:15", "2024-03-30 17:40", "2024-03-31 23:05"]),
"end": pd.to_datetime(["2024-03-29 08:42", "2024-03-30 18:31", "2024-04-01 00:10"]),
})
rides["duration"] = rides["end"] - rides["start"]
rides["minutes"] = rides["duration"].dt.total_seconds() / 60
print(rides)
print("Longest ride:", rides["duration"].max())
deadline = pd.Timestamp("2024-04-01") + pd.Timedelta(days=14)
print("Deadline:", deadline.date()) start end duration minutes
0 2024-03-29 08:15:00 2024-03-29 08:42:00 0 days 00:27:00 27.0
1 2024-03-30 17:40:00 2024-03-30 18:31:00 0 days 00:51:00 51.0
2 2024-03-31 23:05:00 2024-04-01 00:10:00 0 days 01:05:00 65.0
Longest ride: 0 days 01:05:00
Deadline: 2024-04-15
Notice the third ride crosses midnight and is still computed correctly.
Date ranges
pd.date_range() creates a sequence of dates with a given frequency: "D" daily, "W" weekly, "h" hourly, "MS" month start, "ME" month end, "B" business days:
import pandas as pd
print(pd.date_range("2024-01-29", periods=5, freq="D"))
print(pd.date_range("2024-01-01", "2024-04-30", freq="MS").strftime("%b %d").to_list())
print(len(pd.date_range("2024-07-01", "2024-07-31", freq="B")), "business days in July 2024")DatetimeIndex(['2024-01-29', '2024-01-30', '2024-01-31', '2024-02-01',
'2024-02-02'],
dtype='datetime64[ns]', freq='D')
['Jan 01', 'Feb 01', 'Mar 01', 'Apr 01']
23 business days in July 2024
Time series: a DatetimeIndex
When dates are the index, you can select with partial date strings: "2024-02" means "all of February":
import pandas as pd
days = pd.date_range("2024-01-25", periods=12, freq="D")
visitors = pd.Series(range(100, 220, 10), index=days, name="visitors")
print(visitors.loc["2024-02"])
print(visitors.loc["2024-01-30":"2024-02-01"])
print(visitors[visitors.index.dayofweek == 6]) # Sundays only2024-02-01 170
2024-02-02 180
2024-02-03 190
2024-02-04 200
2024-02-05 210
Freq: D, Name: visitors, dtype: int64
2024-01-30 150
2024-01-31 160
2024-02-01 170
Freq: D, Name: visitors, dtype: int64
2024-01-28 130
2024-02-04 200
Name: visitors, dtype: int64
To aggregate a time series by week or month, use resample(), covered in its own lesson.
Note: Timestamps can also carry a time zone:
s.dt.tz_localize("Europe/Paris")attaches one and.dt.tz_convert("UTC")converts. Mixing naive and time-zone-aware values raises an error, so be consistent.
Test yourself
How do you get the month number from a datetime column d?
- d.month
- d.dt.month
- d.str.month
- month(d)
What is the result of subtracting one datetime column from another?
- A float in days
- A Timedelta (duration)
- A string
- An error
With a DatetimeIndex, what does s.loc["2024-03"] select?
- Only March 1st
- Every row in March 2024
- The third row
- An error