Pandas.to_datetime()-Python
pandas.to_datetime() converts argument(s) to datetime. This function is essential for working with date and time data, especially when parsing strings or timestamps into Python's datetime64 format used in Pandas.
For Example:
import pandas as pd
d = ['2025-06-21', '2025-06-22']
res = pd.to_datetime(d)
print(res)
Output
DatetimeIndex(['2025-06-21', '2025-06-22'], dtype='datetime64[ns]', freq=None)
Explanation: date strings are in ISO format (YYYY-MM-DD), which pandas.to_datetime() parses by default, returning a DatetimeIndex.
Syntax
pandas.to_datetime(arg, errors='raise', format=None, dayfirst=False, ...)
Parameters:
Parameter | Description |
---|---|
arg | Input data to convert (e.g., scalar, list, Series, DataFrame). |
errors | How to handle invalid parsing: 'raise' (default), 'coerce' (sets errors to NaT), 'ignore'. |
format | Custom date format for parsing (e.g. "%d/%m/%Y") |
dayfirst | If True, treats the first part of the date as the day (e.g., 31/12/2025). |
yearfirst | If True, treats the first part as the year (e.g., 2025-12-31). |
utc | If True, returns dates in UTC timezone. |
unit | Specifies time unit if input is numeric ('s', 'ms', 'ns', etc.). |
origin | Reference date for numeric timestamps ('unix' or a specific date like '1960-01-01'). |
cache | If True, enables caching to improve performance for repeated strings. |
Returns: A datetime64 dtype object, which can be a single Timestamp, DatetimeIndex or Series, depending on the input.
Examples
Example 1: In this example, we convert date strings written in DD/MM/YYYY format to datetime objects using the format parameter.
import pandas as pd
d = ['21/06/2025', '22/06/2025']
res = pd.to_datetime(d, format='%d/%m/%Y')
print(res)
Output
DatetimeIndex(['2025-06-21', '2025-06-22'], dtype='datetime64[ns]', freq=None)
Explanation: pandas.to_datetime() expects dates in ISO format (YYYY-MM-DD), so we use 'format='%d/%m/%Y' to correctly parse day-first strings. It converts them into datetime objects and returns a DatetimeIndex holding datetime64 values.
Example 2: In this example, we convert a list of date strings and handle invalid entries using errors='coerce', which replaces the invalid value with NaT.
import pandas as pd
d = ['2025-06-21', 'invalid']
res = pd.to_datetime(d, errors='coerce')
print(res)
Output
DatetimeIndex(['2025-06-21', 'NaT'], dtype='datetime64[ns]', freq=None)
Explanation: pandas.to_datetime() attempts to parse each string, but since 'invalid' is not a valid date, using errors='coerce' replaces it with NaT instead of raising an error, ensuring safe and error-free conversion.
Example 3: In this example, we convert a column of string dates in a DataFrame to datetime format using pd.to_datetime() for further time-based operations.
import pandas as pd
df = pd.DataFrame({'date': ['2025-06-21', '2025-06-22']})
df['date'] = pd.to_datetime(df['date'])
print(df)
Output
date 0 2025-06-21 1 2025-06-22
Explanation: pd.to_datetime() is applied to the 'date' column to convert string values into datetime objects.
Example 4: In this example, we parse dates where the day comes before the month by setting dayfirst=True.
import pandas as pd
d = ['21/06/2025', '22/06/2025']
res = pd.to_datetime(d, dayfirst=True)
print(res)
Output
DatetimeIndex(['2025-06-21', '2025-06-22'], dtype='datetime64[ns]', freq=None)
Explanation: By setting dayfirst=True, pandas.to_datetime() correctly interprets the first number as the day, not the month, ensuring accurate conversion to datetime objects.
Example 5: In this example, we convert a list of integers into dates by treating them as day offsets from the origin date '2025-06-01'.
import pandas as pd
d = [0, 1, 2]
res = pd.to_datetime(d, unit='D', origin='2025-06-01')
print(res)
Output
DatetimeIndex(['2025-06-01', '2025-06-02', '2025-06-03'], dtype='datetime64[ns]', freq=None)
Explanation: By setting unit='D' and specifying the origin, pandas calculates and returns the corresponding datetime values as a DatetimeIndex.
Example 6: In this example, we convert a datetime string into UTC timezone-aware datetime using utc=True.
import pandas as pd
d = ['2025-06-21 12:00']
res = pd.to_datetime(d, utc=True)
print(res)
Output
DatetimeIndex(['2025-06-21 12:00:00+00:00'], dtype='datetime64[ns, UTC]', freq=None)
Explanation: By passing utc=True, pandas.to_datetime() converts the datetime into a timezone-aware datetime in UTC (Coordinated Universal Time).