How to format dates with Pandas

1 min readGetting StartedDataFramePandas
7-Day Challenge

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.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

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


7-Day Challenge

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.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

Free Newsletter

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. 📚

Weekly simple and practical lessons
Access to ready to use code examples
Skip the math, focus on results
Learn while drinking your coffee

By subscribing, you agree to receive our newsletter. You can unsubscribe at any time.