This lesson on Working with Date & Time is hands-on and example-driven. You will learn how to convert string-based date and time data into the specialized Pandas datetime format. This conversion unlocks powerful time series functionality, allowing you to easily extract components like year or hour and perform comparisons and mathematical operations. You will also learn how to aggregate and visualize time series data.
What You'll Be Able To Do
- Convert a Pandas Series of date strings into the
datetime64format usingpd.to_datetime(). - Extract specific time components (e.g., hour, day of year) using the
.dtaccessor. - Perform logical comparisons between a datetime Series and a single Timestamp object.
- Calculate the difference between two Timestamps, resulting in a Timedelta object.
- Aggregate and plot time series data by extracting and counting time components like the year.
Detailed Concept Walkthrough
1. Converting to Datetime Format
Pandas requires dates and times to be in the specialized datetime64 format to enable time series analysis. The pd.to_datetime() function automatically parses common date string formats.
- Mechanism:
pd.to_datetime()takes a Series of strings and attempts to infer the format for each entry, converting them intoTimestampobjects within adatetime64Series. - Best Practice: Avoid brittle string slicing for extraction; always convert the column first to leverage built-in, robust datetime functionality.
- Under the Hood: The resulting Series has a
dtypeofdatetime64[ns], which stores the date/time as a large integer representing nanoseconds since the epoch (Jan 1, 1970).
import pandas as pd
# Assuming UFO['time'] is a Series of date strings
UFO['time'] = pd.to_datetime(UFO['time'])
# The dtype is now datetime64[ns]
Key Takeaway: Convert date strings using
pd.to_datetime()to unlock all time series features in Pandas.
2. Extracting Time Components
Once a column is in the datetime format, the .dt accessor provides a namespace to easily pull out specific attributes like the hour, day name, or year.
- Mechanism: The
.dtaccessor is applied directly to a datetime Series and exposes properties (like.hour,.year) and methods (like.weekday_name) that return new Series containing the extracted values. - Best Practice: Use
.dt.weekday_nameor.dt.weekdayto analyze data by day of the week without writing custom mapping or conversion code. - Syntax Rule: The accessor must be chained:
Series.dt.attribute. It cannot be used on non-datetime Series.
# Assuming UFO['time'] is datetime64
hour_series = UFO['time'].dt.hour
print(UFO['time'].dt.weekday_name.head())
Key Takeaway: Use the
.dtaccessor to quickly and reliably extract any component from a datetime Series.
3. Datetime Math and Comparisons
Pandas allows direct comparison and mathematical operations between datetime objects, enabling filtering by time range and calculating durations.
- Mechanism: A single date string converted by
pd.to_datetime()results in aTimestampobject, which can be compared directly against an entire datetime Series. - Execution Flow: Comparisons (e.g.,
>) return a boolean Series used for filtering rows via.loc[]based on time thresholds. - Under the Hood: Subtracting one Timestamp from another (e.g., Max - Min) yields a
Timedeltaobject, which represents a duration and has its own attributes like.days.
TS = pd.to_datetime('1/1/1999')
recent = UFO.loc[UFO['time'] >= TS, :]
duration = UFO['time'].max() - UFO['time'].min()
Key Takeaway: Datetime objects support standard mathematical and comparison operators for powerful time-based filtering and duration calculation.
Topics Covered in Working with Date & Time
- Introduction to Time Series (0:20 - 0:40) — The lesson introduces the powerful time series functionality available in the Pandas library.
- String Slicing Pitfall (0:50 - 1:30) — The instructor demonstrates using string slicing to extract the hour, noting that this approach is brittle and easily broken.
- Converting to Datetime (1:35 - 2:40) — The 'time' column is converted using
pd.to_datetime(), changing the column's data type todatetime64. - Using the .dt Accessor (2:45 - 3:45) — The
.dtnamespace is used to easily extract attributes like.hour,.weekday_name, and.dayofyearfrom the datetime Series. - Creating a Timestamp (3:55 - 4:45) — A single date string is converted into a
Timestampobject for use in subsequent comparisons. - Datetime Comparisons (4:45 - 5:25) — The DataFrame is filtered using a comparison operator between the datetime Series and the newly created Timestamp object.
- Timedelta Calculation (5:30 - 6:10) — Subtracting the minimum time from the maximum time yields a
Timedeltaobject representing the total duration of the dataset. - Plotting Time Series Data (6:15 - 7:45) — The year is extracted, value counts are calculated, the index is sorted, and the results are plotted chronologically.
Python Cheat Sheet
-
pd.to_datetime(series)— Converts string Series to datetime formatUFO['time'] = pd.to_datetime(UFO['time']) -
Series.dt.attribute— Accesses specific time componentsUFO['time'].dt.year -
Series.dt.weekday_name— Returns the name of the day of the weekUFO['time'].dt.weekday_name.head() -
Timestamp comparison— Filters data based on a time thresholdUFO.loc[UFO['time'] >= TS, :] -
Timestamp subtraction— Calculates the duration between two pointsUFO['time'].max() - UFO['time'].min() -
Timedelta.days— Extracts the total number of days from durationduration.days -
Series.sort_index().plot()— Orders counts by index and generates a plotcounts.sort_index().plot() -
pd.to_datetime('1/1/1999')— Creates a single Timestamp objectTS = pd.to_datetime('1/1/1999')
Comparison Table
| Method | Data Type | Flexibility/Robustness |
|---|---|---|
| String Slicing | object (string) | Brittle; breaks easily with format changes. |
pd.to_datetime() | datetime64[ns] | Robust; infers formats automatically. |
| Datetime Attributes | datetime64[ns] | Allows extraction of hour, year, weekday name. |
Common Pitfalls
- Mistake: Trying to use
.dtaccessor on a string column. Avoid: Ensure the columndtypeisdatetime64before using.dt. - Mistake: Relying on string slicing to extract time components.
Avoid: Use
pd.to_datetime()for robust, format-independent extraction. - Mistake: Comparing a datetime Series to a plain date string.
Avoid: Convert the comparison date into a
Timestampusingpd.to_datetime(). - Mistake: Forgetting to sort the index before plotting counts by year.
Avoid: Chain
.sort_index()before.plot()to ensure chronological order.
FAQs
- What if
pd.to_datetime()doesn't automatically figure out my date format? Thepd.to_datetime()function accepts aformatargument where you can explicitly specify the expected date string structure using standard format codes. - What is the difference between a Timestamp and a Timedelta? A Timestamp represents a specific point in time (e.g., June 1, 1930). A Timedelta represents a duration or difference between two points in time (e.g., 25,781 days).
- Why is string slicing considered brittle for date extraction? String slicing relies on fixed character positions; if the source format changes, the slice will extract the wrong characters.
- How do I see all available attributes under the
.dtaccessor? Consult the official Pandas API reference documentation for the Series.dtproperties and methods to see all available extraction options.