0

I am trying to convert my datetime column to date.

Here is how my date value looks:

2023-06-25T00:00:00.000Z

and I want to convert it to

2023-06-25

This command;

df['date'].dt.strftime('%Y-%m-%d') 

does not work.
The error message that I am getting states "Attribute Error: Can only use .dt accessor with datetime like values".

Also, when I run

df.info 

it is stating that date is an object.

Any ideas on what I can do?

moken
  • 3,227
  • 8
  • 13
  • 23
Ty Kendall
  • 13
  • 3
  • What does your console look like when you print `df["date"]`? – Roj Jul 30 '23 at 17:13
  • If it's saying the dtype is object, there's probably some non-datetime values in the column. – Barmar Jul 30 '23 at 17:14
  • You should first try to convert the column to datetime, see https://stackoverflow.com/questions/28133018/convert-pandas-series-to-datetime-in-a-dataframe – Barmar Jul 30 '23 at 17:15

2 Answers2

1
import pandas as pd

# Assuming 'df' is your DataFrame
# Convert 'date' column to datetime format
df['date'] = pd.to_datetime(df['date'])

# Extract only the date part and overwrite the 'date' column
df['date'] = df['date'].dt.date

# Now, 'date' column will contain only the date (yyyy-mm-dd)
print(df['date'])
0

To change from object to datetime64 you can try this:

import pandas as pd


data = {'date': ['2023-06-25T00:00:00.000Z']}
df = pd.DataFrame(data)

df['date'] = pd.to_datetime(df['date'])

df['date'] = df['date'].dt.strftime('%Y-%m-%d')

print(df)

And if you do df.info() it will say datetime64, not object

setibs
  • 24
  • 3