DateTime in Python
Datetime handling enables time-based analysis.
Parsing
pd.to_datetime converts strings to datetime. format parameter specifies format: '%Y-%m-%d'.
datetime64[ns] is pandas datetime type. .dt accessor provides datetime methods.
Components
Extract components: .dt.year, .dt.month, .dt.day, .dt.dayofweek, .dt.hour.
Resample aggregates by time period: df.resample('D').mean() for daily, 'M' for monthly.
Time Zones
Timezone localization: dt.tz_localize('UTC'). Conversion: dt.tz_convert('US/Eastern').
Handling time zones prevents errors in global data.
Key Takeaways
- Pandas provides powerful datetime handling
- .dt accessor extracts datetime components
- Resample enables time-based aggregation