Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas pd.to_datetime() function

Pandas pd.to_datetime() function

Pandas Universal Functions Common Pandas functions


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


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'

]

)

print

(

"=== Original Series (dtype:"

,

dates.

dtype

,

")==="

)

print

(

dates

)

2. Converting to datetime with pd.to_datetime()

result

=

pd.

to_datetime

(

dates

)

print

(

"\n=== After pd.to_datetime() conversion (dtype:"

,

result.

dtype

,

")==="

)

print

(

result

)

3. Supporting multiple formats

dates_mixed

=

pd.

Series

(

[

   

'2023-01-01'

,

   

'2023/02/03'

,

   

'01.04.2023'

,

   

'2023-05-06'

]

)

print

(

"\n=== Automatic parsing of multiple formats ==="

)

print

(

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

)

print

(

"\n=== Information including time ==="

)

print

(

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:

  1. pd.to_datetime() It can automatically recognize many common datetime formats.
  2. Even if the input contains only a date, the time part is filled with 00:00:00 by default.
  3. 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'

]

)

print

(

"=== European date format (01/02/2023 interpreted as the 2nd) ==="

)

print

(

"Default (month/day/year):"

,

pd.

to_datetime

(

europe_dates

)

.

dt

.

day

.

tolist

(

)

)

print

(

"dayfirst=True:"

,

pd.

to_datetime

(

europe_dates

,

dayfirst

=

True

)

.

dt

.

day

.

tolist

(

)

)

2. Specifying an exact format with the format argument

print

(

"\n=== Using the format argument ==="

)

result

=

pd.

to_datetime

(

'2023-06-15 14:30:00'

,

format

=

'%Y-%m-%d %H:%M:%S'

)

print

(

f

"Conversion result: {result}"

)

3. Parsing complex formats

complex_dates

=

pd.

Series

(

[

'2023-12-25'

,

'15/08/2023'

,

'2023-05-01'

]

)

print

(

"\n=== Automatic parsing of mixed formats ==="

)

print

(

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:

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

]

)

print

(

"=== Unix timestamp (seconds) ==="

)

print

(

timestamps.

values

)

2. Converting to datetime

result

=

pd.

to_datetime

(

timestamps

,

unit

=

's'

)

print

(

"\n=== After pd.to_datetime(..., unit='s') conversion ==="

)

print

(

result

)

3. Unix timestamp (milliseconds)

timestamps_ms

=

pd.

Series

(

[

1672531200000

,

1672617600000

,

1672704000000

]

)

result_ms

=

pd.

to_datetime

(

timestamps_ms

,

unit

=

'ms'

)

print

(

"\n=== Millisecond timestamp ==="

)

print

(

result_ms

)

4. Converting from a fixed origin

print

(

"\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'

)

print

(

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:

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'

]

)

print

(

"=== Series containing invalid dates ==="

)

print

(

mixed_dates

)

2. errors='raise' (default) - raise an exception

print

(

"\n=== errors='raise' ==="

)

try

:

    pd.

to_datetime

(

mixed_dates

,

errors

=

'raise'

)

except

Exception

as

e:

   

print

(

f

"Exception: {type(e).name}"

)

3. errors='coerce' - convert invalid dates to NaT

print

(

"\n=== errors='coerce' ==="

)

result

=

pd.

to_datetime

(

mixed_dates

,

errors

=

'coerce'

)

print

(

result

)

4. errors='ignore' - keep the original values

print

(

"\n=== errors='ignore' ==="

)

result_ignore

=

pd.

to_datetime

(

mixed_dates

,

errors

=

'ignore'

)

print

(

result_ignore

)

print

(

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:


Notes

Important note:

  • If a value in the data is outside the datetime range, an exception will be raised OutOfBoundsDatetime exception.
  • format The argument can explicitly specify the date format; it is recommended for large datasets to improve performance.
  • The converted datetime objects can use .dt the accessor for rich datetime operations.
  • Time zone handling requires installing pytz library.

  • Python math Module Common Pandas functions