Pandas — DateTime
Convert to datetime
import pandas as pd
df = pd.DataFrame({'date': ['2024-01-01', '2024-01-02', '2024-01-03']})
df['date'] = pd.to_datetime(df['date'])
Extract components
df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month
df['day'] = df['date'].dt.day
df['day_name'] = df['date'].dt.day_name()
Date arithmetic
df['next_week'] = df['date'] + pd.Timedelta(days=7)
df['days_diff'] = df['date'] - pd.Timestamp('2024-01-01')
Date range
dates = pd.date_range(start='2024-01-01', end='2024-12-31', freq='D')
Mini Practice
- Convert to datetime
- Extract components
- Perform date arithmetic
- Create date ranges
Up Next
Continue with Timedelta - Time differences.
Related Topics
Frequently Asked Questions about DateTime
What is DateTime in Pandas?
DateTime is a fundamental concept in Pandas. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn DateTime?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn DateTime.
Why is DateTime important in Pandas?
DateTime is essential for Pandas development. Understanding this concept will help you write better code and solve real-world problems more effectively.