How to format dates with Pandas
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
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})
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"])
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')
and
pd.to_datetime(1627941644123, unit='ms')
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
Related Articles
Continue your learning journey with these related topics
Master Data Science in Days, Not Months 🚀
Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚