Time is Money: Save Both with Pandas DateTime
Pandas provide extensive functionality for working with dates and times.
Pandas is a Python library which provides data structures and data analysis tools. One of its key features is its ability to work with dates and times.
The pandas.to_datetime() function can convert a variety of date/time formats into a DateTime object, which is the basic date/time data type in pandas.
Additionally, pandas provides powerful time series functionality, such as resampling and moving window operations, using the pandas.
DataFrame.resample() and pandas.DataFrame.rolling() methods, respectively. Here are a few common tasks you might perform using Pandas’ datetime functionality:
Converting strings to datetime objects: You can use the pd.to_datetime function to convert strings to datetime objects. For example:
import pandas as pd
# Convert a string to a datetime object
datestring = '2022-12-19'
date = pd.to_datetime(datestring)
print(date)
# Output: 2022-12-19 00:00:00
Extracting parts of a datetime object: You can use the dt attribute of a datetime object to extract parts of the date, such as the year, month, or day. For example:
# Extract the year from a datetime object
year = date.year
print(year) # Output: 2022
# Extract the month from a datetime object
month = date.month
print(month) # Output: 12
# Extract the day from a datetime object
day = date.day
print(day) # Output: 19
Manipulating datetime objects: You can use the timedelta class to perform arithmetic on datetime objects, such as adding or subtracting time. For example:
# Add two days to a datetime object
from datetime import timedelta
new_date = date + timedelta(days=2)
print(new_date) # Output: 2022-12-21 00:00:00
# Subtract one week from a datetime object
prev_week = date - timedelta(weeks=1)
print(prev_week) # Output: 2022-12-12 00:00:00
Formatting datetime objects: You can use the strftime method of a datetime object to format the date as a string in a specific format. For example:
# Format a datetime object as a string in the 'YYYY-MM-DD' format
date = datetime.now()
formatted_date = date.strftime('%Y-%m-%d')
print(formatted_date) # Output: '2022-12-19'