0
0
Pandasdata~5 mins

Datetime type in Pandas

Choose your learning style9 modes available
Introduction

Datetime type helps us work with dates and times easily. It makes it simple to analyze and compare dates in data.

You want to find how many days passed between two events.
You need to sort data by date, like sales over time.
You want to extract parts of a date, like the month or year.
You want to filter data for a specific date range.
You want to plot data over time to see trends.
Syntax
Pandas
pd.to_datetime(data)

data can be a string, list, or column with date info.

This converts data into pandas datetime type for easy date operations.

Examples
Convert one date string to datetime type.
Pandas
import pandas as pd

# Convert a single date string
date = pd.to_datetime('2024-06-01')
print(date)
Convert a list of date strings to datetime type.
Pandas
import pandas as pd
dates = ['2024-01-01', '2024-02-15', '2024-03-30']
dates_dt = pd.to_datetime(dates)
print(dates_dt)
Convert a DataFrame column with date strings to datetime type.
Pandas
import pandas as pd
df = pd.DataFrame({'date_str': ['2024-01-01', '2024-02-15', '2024-03-30']})
df['date'] = pd.to_datetime(df['date_str'])
print(df)
Sample Program

This program converts date strings to datetime type, then calculates how many days passed since the first event.

Pandas
import pandas as pd

# Create a DataFrame with date strings
data = {'event': ['start', 'middle', 'end'],
        'date_str': ['2024-01-01', '2024-06-15', '2024-12-31']}
df = pd.DataFrame(data)

# Convert the date_str column to datetime type
df['date'] = pd.to_datetime(df['date_str'])

# Calculate days since start for each event
df['days_since_start'] = (df['date'] - df['date'].min()).dt.days

print(df)
OutputSuccess
Important Notes

Datetime type allows easy date math like subtraction to find durations.

Use .dt accessor to get parts like year, month, day from datetime columns.

Always convert date strings to datetime type before date operations for accuracy.

Summary

Datetime type stores dates and times in a way pandas understands.

Use pd.to_datetime() to convert strings to datetime type.

Datetime type makes date calculations and filtering simple and reliable.