Movatterモバイル変換


[0]ホーム

URL:


Open In App

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.

ForExample:

Python
importpandasaspdd=['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), whichpandas.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 inDD/MM/YYYY format to datetime objects using the format parameter.

Python
importpandasaspdd=['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 usingerrors='coerce', which replaces the invalid value withNaT.

Python
importpandasaspdd=['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, usingerrors='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 usingpd.to_datetime() for further time-based operations.

Python
importpandasaspddf=pd.DataFrame({'date':['2025-06-21','2025-06-22']})df['date']=pd.to_datetime(df['date'])print(df)

Output
        date0 2025-06-211 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 settingdayfirst=True.

Python
importpandasaspdd=['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 settingdayfirst=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'.

Python
importpandasaspdd=[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 usingutc=True.

Python
importpandasaspdd=['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 passingutc=True,pandas.to_datetime()converts the datetime into a timezone-aware datetime in UTC (Coordinated Universal Time).


Improve

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp