Page7/14
Working with Time Series Β· Page 1 of 1
Parsing & Extracting Dates
Working with Time Series
Why Dates are Tricky
CSV files load dates as strings: "2023-10-05". You cannot add or subtract strings mathematically.
Converting to Datetime
df['date'] = pd.to_datetime(df['date_string'])
Once converted, you unlock powerful features:
- Extract parts:
df['date'].dt.year,.dt.month,.dt.day_name() - Time math:
df['date'] + pd.Timedelta(days=7) - Filter ranges:
df[(df['date'] > '2023-01-01') & (df['date'] < '2023-12-31')]
Setting the Index
For time-series analysis (stock prices, sensor data), set the date as the DataFrame index:
df.set_index('date', inplace=True)
Pro Tip: Always use
format=into_datetimeif your date string is weird (e.g.,"05/10/2023"vs"10-05-2023"). It makes parsing 10x faster.
main.py
Loading...
OUTPUT
βΆClick "Run Code" to executeβ¦