to_datetime()

noun

say it: “too DAYT-tym” /tu ˈdeɪtˌtaɪm/

A pandas function that turns text such as "07/23/2007" into real dates, so they sort and compare by time instead of letter by letter.

What does to_datetime() do in pandas?

to_datetime() (pd.to_datetime) turns text such as "07/23/2007" into real dates that sort and compare by time. format= says exactly how the dates were written, and errors="coerce" turns each date it can't read into NaT, so you can list them.

import pandas as pd
born = pd.Series(["07/23/2007", "02/30/2008"])
print(pd.to_datetime(born, format="%m/%d/%Y", errors="coerce"))
# 0   2007-07-23
# 1          NaT    (February 30 doesn't exist)

In a sentence

  • “to_datetime() turned the birth dates into real dates, so the youngest runner sorted last.”
  • “With errors="coerce", to_datetime() made the impossible February 30 into NaT.”

Level: Journeyman · More Python terms at this level

Updated