Pandas pd.to_datetime() function
pd.to_datetime() is a function in the Pandas library used toConvert data to datetime typefunction. It can convert data in various formats such as strings and Unix timestamps into Pandas' datetime64 type.
Date-time processing is a common task in data analysis. After conversion to datetime, you can easily perform date extraction, time arithmetic, timezone handling, and other operations.
Word meaning: to_datetime It means "convert to datetime", i.e., uniformly convert time data in various formats into standard datetime objects.
Basic syntax and parameters
pd.to_datetime() is a top-level function in the Pandas library used to convert time data in various formats to datetime type.
Syntax format
pd.to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False, utc=False, format=None, unit='ns')
Parameter Description
| Parameters | Type | Description |
|---|---|---|
| arg | int, float, str, datetime, list, Series | The data to convert to datetime type. |
| errors | String | Error handling: 'raise' (default) raises an exception; 'coerce' converts to NaT; 'ignore' returns the original data. |
| dayfirst | Boolean | If True, the day is placed before the month (e.g., 01/02/2023 means the 2nd). |
| utc | Boolean | If True, returns a UTC-timezone datetime. |
| format | String | Specifies the datetime format, e.g., '%Y-%m-%d'. |
| unit | String | When arg is numeric, specifies the unit: 'D', 's', 'ms', 'us', 'ns'. |
Return value description
- Return Value: Returns a Series of datetime64 type.
- effect: Converts input data to Pandas datetime type for convenient datetime operations.
Example
Let us thoroughly master pd.to_datetime() through a series of examples from simple to complex.
Example 1: Basic usage - converting strings to datetime
Example
import
pandas
as
pd
1. Creating a Series of datetime strings
dates
=
pd.
Series
(
[
'2023-01-01'
,
'2023-01-02'
,
'2023-01-03'
,
'2023-01-04'
,
'2023-01-05'
]
)
(
"=== Original Series (dtype:"
,
dates.
dtype
,
")==="
)
(
dates
)
2. Converting to datetime with pd.to_datetime()
result
=
pd.
to_datetime
(
dates
)
(
"\n=== After pd.to_datetime() conversion (dtype:"
,
result.
dtype
,
")==="
)
(
result
)
3. Supporting multiple formats
dates_mixed
=
pd.
Series
(
[
'2023-01-01'
,
'2023/02/03'
,
'01.04.2023'
,
'2023-05-06'
]
)
(
"\n=== Automatic parsing of multiple formats ==="
)
(
pd.
to_datetime
(
dates_mixed
)
)
4. Including time information
dates_with_time
=
pd.
Series
(
[
'2023-01-01 12:30:45'
,
'2023-02-03 08:15:30'
]
)
result_datetime
=
pd.
to_datetime
(
dates_with_time
)
(
"\n=== Information including time ==="
)
(
result_datetime
)
Result:
=== 原始 Series(类型: object )===
0 2023-01-01
1 2023-01-02
2 2023-01-03
3 2023-01-04
4 2023-01-05
dtype: object
=== pd.to_datetime() 转换后(类型: datetime64[ns] )===
0 2023-01-01 00:00:00
1 2023-01-02 00:00:00
2 2023-01-03 00:00:00
3 2023-01-04 00:00:00
4 2023-01-05 00:00:00
=== 多种格式自动解析 ===
0 2023-01-01 00:00:00
1 2023-02-03 00:00:00
2 2023-04-01 00:00:00
3 2023-05-06 00:00:00
=== 包含时间的信息 ===
0 2023-01-01 12:30:45
1 2023-02-03 08:15:30
Code analysis:
pd.to_datetime()It can automatically recognize many common datetime formats.- Even if the input contains only a date, the time part is filled with 00:00:00 by default.
- It can handle date formats with different separators, including Chinese characters, dots, and slashes.
Example 2: Handling different date formats and the dayfirst argument
For date formats from different regions, you can use dayfirst the parameter or format parameter was added.
Example
import
pandas
as
pd
1. European date format (month/day/year)
europe_dates
=
pd.
Series
(
[
'01/02/2023'
,
'02/03/2023'
,
'03/04/2023'
]
)
(
"=== European date format (01/02/2023 interpreted as the 2nd) ==="
)
(
"Default (month/day/year):"
,
pd.
to_datetime
(
europe_dates
)
.
dt
.
day
.
tolist
(
)
)
(
"dayfirst=True:"
,
pd.
to_datetime
(
europe_dates
,
dayfirst
=
True
)
.
dt
.
day
.
tolist
(
)
)
2. Specifying an exact format with the format argument
(
"\n=== Using the format argument ==="
)
result
=
pd.
to_datetime
(
'2023-06-15 14:30:00'
,
format
=
'%Y-%m-%d %H:%M:%S'
)
(
f
"Conversion result: {result}"
)
3. Parsing complex formats
complex_dates
=
pd.
Series
(
[
'2023-12-25'
,
'15/08/2023'
,
'2023-05-01'
]
)
(
"\n=== Automatic parsing of mixed formats ==="
)
(
pd.
to_datetime
(
complex_dates
,
dayfirst
=
True
)
)
Result:
=== 欧洲格式日期(01/02/2023 理解为 2 号)===
默认: [1, 2, 3]
dayfirst=True: [2, 3, 4]
=== 使用 format 参数 ===
转换结果: 2023-06-15 14:30:00
=== 混合格式自动解析 ===
0 2023-12-25 00:00:00
1 2023-08-15 00:00:00
2 2023-05-01 00:00:00
Code analysis:
formatSpecifying an exact format with the argument tells Pandas clearly how to parse dates and avoids ambiguity.- Automatic parsing is powerful, but in ambiguous cases (such as interpreting 01/02/2023), you need to use
dayfirstorformatthe argument to specify explicitly.
Example 3: Converting Unix timestamps to datetime
Timestamps exported from a database or system can be converted using unit the argument.
Example
import
pandas
as
pd
1. Unix timestamp (seconds)
timestamps
=
pd.
Series
(
[
1672531200
,
1672617600
,
1672704000
]
)
(
"=== Unix timestamp (seconds) ==="
)
(
timestamps.
values
)
2. Converting to datetime
result
=
pd.
to_datetime
(
timestamps
,
unit
=
's'
)
(
"\n=== After pd.to_datetime(..., unit='s') conversion ==="
)
(
result
)
3. Unix timestamp (milliseconds)
timestamps_ms
=
pd.
Series
(
[
1672531200000
,
1672617600000
,
1672704000000
]
)
result_ms
=
pd.
to_datetime
(
timestamps_ms
,
unit
=
'ms'
)
(
"\n=== Millisecond timestamp ==="
)
(
result_ms
)
4. Converting from a fixed origin
(
"\n=== Counting from 2023-01-01 ==="
)
days
=
pd.
Series
(
[
0
,
1
,
2
,
3
,
4
]
)
result_origin
=
pd.
to_datetime
(
days
,
origin
=
'2023-01-01'
,
unit
=
'D'
)
(
result_origin
)
Result:
=== Unix 时间戳(秒)===
[1672531200 1672617600 1672704000]
=== pd.to_datetime(..., unit='s') 转换后 ===
0 2023-01-01 00:00:00
1 2023-01-02 00:00:00
2 2023-01-03 00:00:00
=== 毫秒级时间戳 ===
0 2023-01-01 00:00:00
1 2023-01-02 00:00:00
2 2023-01-03 00:00:00
=== 从 2023-01-01 开始计算 ===
0 2023-01-01
1 2023-01-02
2 2023-01-03
3 2023-01-04
4 2023-01-05
Code analysis:
unit='s'It indicates the numeric unit is seconds (Unix timestamp).unit='ms'It indicates a millisecond timestamp.originThe argument can specify the origin time for computing relative time.
Example 4: Handling invalid dates with the errors argument
Example
import
pandas
as
pd
import
numpy
as
np
1. A Series containing invalid dates
mixed_dates
=
pd.
Series
(
[
'2023-01-01'
,
'2023-02-30'
,
'invalid'
,
'2023-03-15'
]
)
(
"=== Series containing invalid dates ==="
)
(
mixed_dates
)
2. errors='raise' (default) - raise an exception
(
"\n=== errors='raise' ==="
)
try
:
pd.
to_datetime
(
mixed_dates
,
errors
=
'raise'
)
except
Exception
as
e:
(
f
"Exception: {type(e).name}"
)
3. errors='coerce' - convert invalid dates to NaT
(
"\n=== errors='coerce' ==="
)
result
=
pd.
to_datetime
(
mixed_dates
,
errors
=
'coerce'
)
(
result
)
4. errors='ignore' - keep the original values
(
"\n=== errors='ignore' ==="
)
result_ignore
=
pd.
to_datetime
(
mixed_dates
,
errors
=
'ignore'
)
(
result_ignore
)
(
f
"dtype: {result_ignore.dtype}"
)
Result:
=== 包含无效日期的 Series ===
0 2023-01-01
1 2023-02-30
2 invalid
3 2023-03-15
=== errors='raise' ===
异常: OutOfBoundsDatetime
=== errors='coerce' ===
0 2023-01-01 00:00:00
1 NaT
2 NaT
3 2023-03-15 00:00:00
=== errors='ignore' ===
0 2023-01-01
1 2023-02-30
2 invalid
3 2023-03-15
dtype: object
Code analysis:
errors='coerce'It converts both invalid dates and unparseable values to NaT (Not a Time, equivalent to a missing value).- This is very useful when working with dirty data, as it keeps data processing continuous.
Notes
Important note:
OutOfBoundsDatetime exception.format The argument can explicitly specify the date format; it is recommended for large datasets to improve performance..dt the accessor for rich datetime operations.pytz library.
Common Pandas functions