How to format dates with Pandas

1 min

Formatting a date column is quite simple using Pandas to_datetime()

import pandas as pd

my_date_list = ["2021-01-01","2021-01-02","2021-01-03","2021-01-04"]
df = pd.DataFrame({"datetime":my_date_list})
Our dates are string objects

Now if you print the datatype of the datetime column, you can see it as dtype: object.

You might want to format it as dates.

You easily can do that using the Pandas to_datetime().

df["datetime"] = pd.to_datetime(df["datetime"])
We format the "datetime" column into date format

What if the format is weird ?

For example you might encounter 1627xxxxxxx example format.

This kind of format might be in seconds or milliseconds, so we need to specify the unit like so.

pd.to_datetime(1627941644, unit='s')
When the date is in unix timestamp in seconds

and

pd.to_datetime(1627941644123, unit='ms')
When the date is in unix timestamp in milliseconds