We use to_datetime() to change text or numbers into dates. This helps us work with dates easily in data.
0
0
to_datetime() conversion in Data Analysis Python
Introduction
You have a list of dates as text and want to sort them by time.
You want to find the difference between two dates in your data.
You need to filter data for a specific month or year.
Your data has dates in different formats and you want to standardize them.
You want to add new columns like day, month, or year from a date column.
Syntax
Data Analysis Python
pandas.to_datetime(arg, format=None, errors='raise', utc=None, dayfirst=False, yearfirst=False)
arg is the data to convert (like a list, column, or string).
format helps speed up conversion if you know the date pattern.
Examples
Converts one date string to a datetime object.
Data Analysis Python
import pandas as pd # Convert a single date string date = pd.to_datetime('2024-06-01') print(date)
Converts a list of date strings to datetime objects.
Data Analysis Python
dates = ['2024-06-01', '2023-12-25', '2024-01-15'] dates_dt = pd.to_datetime(dates) print(dates_dt)
Uses
dayfirst=True because dates are in day/month/year format.Data Analysis Python
dates = ['01/06/2024', '25/12/2023'] dates_dt = pd.to_datetime(dates, dayfirst=True) print(dates_dt)
Specifies the exact format to speed up conversion.
Data Analysis Python
dates = ['20240601', '20231225'] dates_dt = pd.to_datetime(dates, format='%Y%m%d') print(dates_dt)
Sample Program
This code converts a column of date strings to datetime objects. It handles different date formats by setting dayfirst=True. Invalid formats become NaT (missing date).
Data Analysis Python
import pandas as pd data = {'date_text': ['2024-06-01', '2023-12-25', '2024-01-15', '15/07/2024']} df = pd.DataFrame(data) # Convert date_text to datetime, handle dayfirst for last date # Use errors='coerce' to convert invalid formats to NaT df['date'] = pd.to_datetime(df['date_text'], dayfirst=True, errors='coerce') print(df)
OutputSuccess
Important Notes
If a date can't be converted, use errors='coerce' to get NaT instead of an error.
Use format when you know the exact date pattern to make conversion faster.
to_datetime() works well with pandas Series and lists.
Summary
to_datetime() changes text or numbers into date objects.
It helps you sort, filter, and calculate with dates easily.
Use options like dayfirst and format to handle different date styles.