What is the pandas.to_datetime() method?
Pandas is a Python library that is primarily used for data analysis.
Dates are often provided in different formats and must be converted into single format DateTime objects before analysis. This is where pandas.to_datetime() comes in handy.
Let’s go over some of the most frequently used parameters that this function takes:
- arg: an integer, float, string, list, or dict object to convert into a DateTime object.
- dayfirst: set it to true if the input contains the day first.
- yearfirst: set it to true if the input contains the year first.
- utc: returns the UTC DatetimeIndex if True.
- format: specifies the position of the day, month, and year in the date.
Code
Using pandas.to_datetime() with a date
import pandas as pd# input in mm.dd.yyyy formatdate = ['01.02.2019']# output in yyyy-mm-dd formatprint(pd.to_datetime(date))
Using pandas.to_datetime() with a date and time
import pandas as pd# date (mm.dd.yyyy) and time (H:MM:SS)date = ['01.02.2019 1:30:00 PM']# output in yyyy-mm-dd HH:MM:SSprint(pd.to_datetime(date))
Using pandas.to_datetime() with dates in dd-mm-yyyy and yy-mm-dd format
import pandas as pd# pandas interprets this date to be in m-d-yyyy formatprint(pd.to_datetime('8-2-2019'))# if the specified date contains the day first, then# that has to be specified.# output in yyyy-mm-dd format.print(pd.to_datetime('8-2-2019', dayfirst = True))# if the specified date contains the year first, then# that has to be specified.# output in yyyy-mm-dd format.print(pd.to_datetime('10-2-8', yearfirst = True))
Using pandas.to_datetime() to specify a format
import pandas as pddate = '2019-07-31 12:00:00-UTC'print(pd.to_datetime(date, format = '%Y-%m-%d %H:%M:%S-%Z'))
Using pandas.to_datetime() to obtain a timezone-aware timestamp
import pandas as pddate = '2019-01-01T15:00:00+0100'print(pd.to_datetime(date, utc = True))
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved