The pandas library has a powerful set of tools for working with dates and times, located in the datetime
module. In this blog post, we’ll explore some of the ways that you can use this module to manipulate and analyze datetime data in your pandas DataFrames.
CREATING DATETIME OBJECTS
One of the first things you might want to do when working with datetime data in pandas is create datetime objects. You can do this using the pd.to_datetime()
function, which takes a string representation of a date and time and converts it into a datetime object. For example:
1
2
3
4
5
6
7
|
import pandas as pd # Convert a string to a datetime object date_string = "2022-12-18 09:30:00" datetime_object = pd.to_datetime(date_string) print(datetime_object) # 2022-12-18 09:30:00 |
You can also pass a list of strings to pd.to_datetime()
, and it will convert them all to datetime objects in a single call. This can be very useful when you have a large dataset with a lot of datetime data that needs to be cleaned and formatted.
MANIPULATING DATETIME OBJECTS
Once you have datetime objects, there are many ways that you can manipulate them using the datetime
module. For example, you can extract the year, month, or day from a datetime object using the .year
, .month
, and .day
attributes:
1
2
3
4
5
6
7
8
9
10
11
|
import pandas as pd # Extract the year, month, and day from a datetime object datetime_object = pd.to_datetime("2022-12-18 09:30:00") year = datetime_object.year month = datetime_object.month day = datetime_object.day print(year) # 2022 print(month) # 12 print(day) # 18 |
You can also perform arithmetic operations on datetime objects to add or subtract time periods. For example, you can use the timedelta
object from the datetime
module to add or subtract days, hours, minutes, or seconds from a datetime object:
1
2
3
4
5
6
7
|
import pandas as pd from datetime import timedelta # Add or subtract time from a datetime object datetime_object = pd.to_datetime("2022-12-18 09:30:00") new_datetime_object = datetime_object + timedelta(days=7) |
————————–