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:
pandas.to_datetime()
with a dateimport pandas as pd# input in mm.dd.yyyy formatdate = ['01.02.2019']# output in yyyy-mm-dd formatprint(pd.to_datetime(date))
pandas.to_datetime()
with a date and timeimport 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))
pandas.to_datetime()
with dates in dd-mm-yyyy and yy-mm-dd formatimport 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))
pandas.to_datetime()
to specify a formatimport pandas as pddate = '2019-07-31 12:00:00-UTC'print(pd.to_datetime(date, format = '%Y-%m-%d %H:%M:%S-%Z'))
pandas.to_datetime()
to obtain a timezone-aware timestampimport pandas as pddate = '2019-01-01T15:00:00+0100'print(pd.to_datetime(date, utc = True))
Free Resources