Working with Dates and Times
Lesson Introduction
Working with dates and times is crucial in data analysis. Imagine analyzing sales data over time to understand seasonal trends. To make sense of such data, you need to handle dates and times accurately.
Today's goals:
- Convert columns with date info to
datetimeformat, even if they are in different formats. - Extract specific components like the year from
datetimedata. - Perform basic
datetimeoperations such as finding time differences and obtaining today's date.
By the end, you'll be comfortable manipulating dates and times in Pandas. Let's start!
Converting Columns to Datetime
Date info often comes as text, which isn't very useful for analysis. Converting this text to datetime format lets us use powerful features in Pandas.
The pd.to_datetime() function converts different date formats correctly. Here's an example:
Output:
This example converts various date formats into datetime objects, making date operations easier. Note that you need to specify format='mixed', so format will be inferred for each element individually
Extracting Components from Datetime
With a column in datetime format, we can extract components like the year, month, or day using the .dt accessor. Here’s how to extract the year, month, and day:
Output:
This code creates new columns for the year, month, and day, which can be useful for time-based analyses like finding monthly or seasonal trends.
Basic Datetime Operations
Pandas also allows for various datetime operations. For example, finding the time difference between two dates and obtaining today's date:
Output:
This code calculates the time difference between each order date and the current date, as well as retrieves today's date.
