How to Use to_datetime in pandas for Date Conversion
Use
pandas.to_datetime() to convert strings, numbers, or lists into datetime objects in pandas. It automatically parses many date formats and can handle errors or specify formats for faster conversion.Syntax
The basic syntax of pandas.to_datetime() is:
arg: The data to convert (string, list, Series, or DataFrame column).format: Optional. Specify the date format to speed up parsing.errors: Optional. How to handle errors ('raise', 'coerce', 'ignore').utc: Optional. Convert to UTC time zone if True.dayfirst: Optional. Interpret the first value as day (True) or month (False).
python
pandas.to_datetime(arg, format=None, errors='raise', utc=False, dayfirst=False)
Example
This example shows how to convert a list of date strings into pandas datetime objects and how to handle errors by coercing invalid dates to NaT.
python
import pandas as pd dates = ['2023-01-01', '2023/02/15', 'March 3, 2023', 'not a date'] dates_converted = pd.to_datetime(dates, errors='coerce') print(dates_converted)
Output
[Timestamp('2023-01-01 00:00:00') Timestamp('2023-02-15 00:00:00') Timestamp('2023-03-03 00:00:00') NaT]
Common Pitfalls
Common mistakes include:
- Not handling errors, which causes the function to raise exceptions on invalid dates.
- Not specifying
formatwhen the date format is known, which slows down parsing. - Confusing day and month order without setting
dayfirst.
Example of wrong and right usage:
python
import pandas as pd # Wrong: raises error on invalid date try: pd.to_datetime(['2023-13-01']) except Exception as e: print(f'Error: {e}') # Right: coerce invalid dates to NaT dates = pd.to_datetime(['2023-13-01'], errors='coerce') print(dates)
Output
Error: month must be in 1..12
NaT
Quick Reference
| Parameter | Description | Default |
|---|---|---|
| arg | Data to convert (string, list, Series) | Required |
| format | Date format string to speed parsing | None |
| errors | How to handle errors: 'raise', 'coerce', 'ignore' | 'raise' |
| utc | Convert to UTC timezone if True | False |
| dayfirst | Parse day first if True | False |
Key Takeaways
Use pandas.to_datetime() to convert various date formats into datetime objects easily.
Specify the format parameter when you know the date format to speed up conversion.
Use errors='coerce' to handle invalid dates without crashing your code.
Set dayfirst=True if your dates use day before month format.
The function returns pandas Timestamp or NaT for missing/invalid dates.