10.7 C
London
Sunday, July 7, 2024
HomePandas in PythonGeneral Functions in PythonHow to Convert Datetime to Date in Pandas

How to Convert Datetime to Date in Pandas

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

Often you may want to convert a datetime to a date in pandas. Fortunately this is easy to do using the .dt.date function, which takes on the following syntax:

df['date_column'] = pd.to_datetime(df['datetime_column']).dt.date

Example: Datetime to Date in Pandas

For example, suppose we have the following pandas DataFrame:

import pandas as pd

#create pandas DataFrame with two columns
df = pd.DataFrame({'sales': [4, 11],
                   'time': ['2020-01-15 20:02:58', '2020-01-18 14:43:24']})

#view DataFrame 
print(df)

sales	time
0	4	2020-01-15 20:02:58
1	11	2020-01-18 14:43:24

To convert the ‘time’ column to just a date, we can use the following syntax:

#convert datetime column to just date
df['time'] = pd.to_datetime(df['time']).dt.date

#view DataFrame
print(df)

	sales	time
0	4	2020-01-15
1	11	2020-01-18

Now the ‘time’ column just displays the date without the time.

Using Normalize() for datetime64 Dtypes

You should note that the code above will return an object dtype:

#find dtype of each column in DataFrame
df.dtypes

sales     int64
time     object
dtype:   object

If you instead want datetime64 then you can normalize() the time component, which will keep the dtype as datetime64 but it will only display the date:

#convert datetime column to just date
df['time'] = pd.to_datetime(df['time']).dt.normalize()

#view DataFrame
print(df)

	sales	time
0	4	2020-01-15
1	11	2020-01-18

#find dtype of each column in DataFrame
df.dtypes

sales             int64
time     datetime64[ns]
dtype: object

Once again only the date is displayed, but the ‘time’ column is a datetime64 dtype.

Additional Resources

How to Convert Columns to DateTime in Pandas
How to Convert Strings to Float in Pandas

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories