Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pandas

How to return only the date from DateTime column in pandas

abhilash

Overview

We can extract the date from a datetime column in the following ways:

  1. The .dt accessor
  2. The normalize() method

The .dt accessor

The .dt accessor method is used to access the datetime-like properties for the series.

Note: We can refer to .dt accessor to learn more about .dt accessor.

Code example

Let’s look at the code below:

import pandas as pd

df = pd.DataFrame({"timestamp": ["2013-01-01 09:10:12", "2022-01-02 09:10:12", "2022-01-03 09:10:12", "2022-01-04 09:10:12"]})

print(pd.to_datetime(df['timestamp']).dt.date)

Code explanation

  • Line 1: We import the pandas module.
  • Line 3: We create a dataframe df with a timestamp column.
  • Line 5: We access the date part of the timestamp column by accessing the date of dt accessor.

The normalize() method

The normalize() method converts times to midnight. It sets all the values to 00:00:00.

Code example

Let’s look at the code below:

import pandas as pd

df = pd.DataFrame({"timestamp": ["2013-01-01 09:10:12", "2022-01-02 09:10:12", "2022-01-03 09:10:12", "2022-01-04 09:10:12"]})

print(pd.to_datetime(df['timestamp']).dt.normalize())

Code explanation

  • Line 1: We import the pandas module.
  • Line 3: We create a dataframe df with a timestamp column.
  • Line 5: We access the date part of the timestamp column by invoking the normalize() function of the dt accessor.

RELATED TAGS

pandas
RELATED COURSES

View all Courses

Keep Exploring