AttributeError: Can only use .dt accessor with datetimelike values | bobbyhadz (2024)

# Table of Contents

  1. AttributeError: Can only use .dt accessor with datetimelike values
  2. Solving the error by explicitly setting the format
  3. Solve the error when reading a CSV file in Pandas

# AttributeError: Can only use .dt accessor with datetimelike values

The Pandas "AttributeError: Can only use .dt accessor with datetimelikevalues" occurs when you try to access the .dt attribute on a non-datetimevalue.

Use the to_datetime method to convert the values in the column of theDataFrame to datetime type to solve the error.

Here is an example of how the error occurs.

main.py

Copied!

import pandas as pddf = pd.DataFrame({ 'name': ['Alice', 'Bobby', 'Carl', 'Dan'], 'salary': [175.1, 180.2, 190.3, 205.4], 'date': ['2023-01-05', '2023-03-25', '2021-01-24', '2022-01-29']})print(df['date'].dtype) # 👉️ object# ⛔️ AttributeError: Can only use .dt accessor with datetimelike values. Did you mean: 'at'?print(df['date'].dt.year)

AttributeError: Can only use .dt accessor with datetimelike values | bobbyhadz (1)

We tried to access thedtattribute on the date column, however, the values in the column are of typeobject, and not datetime objects.

This would work in the same way if the values in your column were of type str.

You can solve the error by using thepandas.to_datetime() method to convertthe values in the column to datetime objects.

main.py

Copied!

import pandas as pddf = pd.DataFrame({ 'name': ['Alice', 'Bobby', 'Carl', 'Dan'], 'salary': [175.1, 180.2, 190.3, 205.4], 'date': ['2023-01-05', '2023-03-25', '2021-01-24', '2022-01-29']})df['date'] = pd.to_datetime(df['date'], errors='coerce')print(df['date'].dtype) # 👉️ datetime64[ns]print(df['date'].dt.year)

Running the code sample produces the following output.

shell

Copied!

0 20231 20232 20213 2022Name: date, dtype: int32

AttributeError: Can only use .dt accessor with datetimelike values | bobbyhadz (2)

The code for this article is available on GitHub

The pandas.to_datetime() method converts the supplied argument to datetime.

The function can be used to convert a scalar, array-like, Series or aDataFrame to a Pandas datetime object.

If a DataFrame is provided, the method expects that it has at least the columns year, month and day.

Notice that we also set the errors argument to coerce when calling themethod.

When the errors argument is set to "coerce", then values that cannot beparsed are set to pandas.NaT.

By default, the errors argument is set to "raise", which means that anexception is raised for values that cannot be parsed.

If the dates in your column are stored in multiple timezones, set the utcparameter to True.

main.py

Copied!

import pandas as pddf = pd.DataFrame({ 'name': ['Alice', 'Bobby', 'Carl', 'Dan'], 'salary': [175.1, 180.2, 190.3, 205.4], 'date': ['2023-01-05', '2023-03-25', '2021-01-24', '2022-01-29']})df['date'] = pd.to_datetime(df['date'], errors='coerce')print(df['date'].dtype) # 👉️ datetime64[ns]print(df['date'].dt.year)

AttributeError: Can only use .dt accessor with datetimelike values | bobbyhadz (3)

The code for this article is available on GitHub

When the utc parameter is set to True, the to_datetime method alwaysreturns a timezone-aware UTC-localized Timestamp, Series or DatetimeIndex.

By default, the argument is set to False, so inputs don't get converted toUTC.

# Solving the error by explicitly setting the format

In some cases, you might have to explicitly set the format argument whencalling pd.to_datetime().

Here is an example.

main.py

Copied!

import pandas as pddf = pd.DataFrame({ 'name': ['Alice', 'Bobby', 'Carl'], 'salary': [175.1, 180.2, 190.3], 'date': ['2023-01-05 09:30:00', '2023-03-25 06:24:05', '2021-01-24 01:30:04']})df['date'] = pd.to_datetime( df['date'], format="%Y-%m-%d %H:%M:%S", errors='coerce')print(df['date'].dtype) # 👉️ datetime64[ns]print(df['date'].dt.year)

AttributeError: Can only use .dt accessor with datetimelike values | bobbyhadz (4)

The code for this article is available on GitHub

Running the code sample produces the following output.

shell

Copied!

0 20231 20232 2021Name: date, dtype: int32

If your dates only have the date component, you would use the following formatstring instead.

main.py

Copied!

import pandas as pddf = pd.DataFrame({ 'name': ['Alice', 'Bobby', 'Carl'], 'salary': [175.1, 180.2, 190.3], 'date': ['2023-01-05', '2023-03-25', '2021-01-24']})df['date'] = pd.to_datetime( df['date'], format="%Y-%m-%d", errors='coerce')print(df['date'].dtype) # 👉️ datetime64[ns]print(df['date'].dt.year)

AttributeError: Can only use .dt accessor with datetimelike values | bobbyhadz (5)

The code for this article is available on GitHub

The pd.to_datetime() method takes an optional format argument.

The argument is used to specify the format that should be used to parse thestrings in the column.

You can also create a new column in the DataFrame that stores the values of aspecific date or time component, e.g. the year.

main.py

Copied!

import pandas as pddf = pd.DataFrame({ 'name': ['Alice', 'Bobby', 'Carl', 'Dan'], 'salary': [175.1, 180.2, 190.3, 205.4], 'date': ['2023-01-05', '2023-03-25', '2021-01-24', '2022-01-29']})df['date'] = pd.to_datetime(df['date'], errors='coerce')df['year'] = df['date'].dt.strftime('%Y')# name salary date year# 0 Alice 175.1 2023-01-05 2023# 1 Bobby 180.2 2023-03-25 2023# 2 Carl 190.3 2021-01-24 2021# 3 Dan 205.4 2022-01-29 2022print(df)

AttributeError: Can only use .dt accessor with datetimelike values | bobbyhadz (6)

The code for this article is available on GitHub

If you need to view all available directives (e.g. %Y, %m, %d, etc), checkoutthis section of the docs.

You can also check thefollowing articleon how to convert date strings to datetime objects in Python.

# Solve the error when reading a CSV file in Pandas

If you get the error when using thepandas.read_csv()method, you have to supply the parse_dates argument.

main.py

Copied!

import pandas as pdfile_path = 'employees.csv'df = pd.read_csv( file_path, sep=',', parse_dates=['date'], encoding='utf-8')# first_name last_name date# 0 Alice Smith 2023-01-05# 1 Bobby Hadz 2023-03-25# 2 Carl Lemon 2021-01-24print(df)print('-' * 50)print(df['date'].dtype) # datetime64[ns]print('-' * 50)# 0 2023# 1 2023# 2 2021# Name: date, dtype: int32print(df['date'].dt.year)

AttributeError: Can only use .dt accessor with datetimelike values | bobbyhadz (7)

The code for this article is available on GitHub

The pandas.read_csv method reads a comma-separated values (CSV) file in aDataFrame.

We set the parse_dates argument to a list containing the columns we want toparse as datetime objects.

The date column in the DataFrame object now has a type of datetime64 andnot object or str.

# Additional Resources

You can learn more about the related topics by checking out the followingtutorials:

  • AttributeError module 'pandas' has no attribute 'DataFrame'
  • ModuleNotFoundError: No module named 'pandas' in Python
  • FutureWarning: pandas.Int64Index is deprecated and will be removed from pandas in a future version
  • You are trying to merge on int64 and object columns [Fixed]
  • Copy a column from one DataFrame to another in Pandas
  • ValueError: cannot reindex on an axis with duplicate labels
  • ValueError: Length mismatch: Expected axis has X elements, new values have Y elements
  • ValueError: cannot reshape array of size X into shape Y
  • Object arrays cannot be loaded when allow_pickle=False
  • ValueError: Columns must be same length as key [Solved]
  • ValueError: DataFrame constructor not properly called [Fix]
  • Count number of non-NaN values in each column of DataFrame
  • Replace whole String if it contains Substring in Pandas
  • Using pandas.read_csv() with multiple delimiters in Python
AttributeError: Can only use .dt accessor with datetimelike values | bobbyhadz (2024)
Top Articles
How Walmart Connect Is Putting Walmart's Purpose in Motion
Office of Student Financial Assistance – The City University of New York
Tsukihime -A piece of blue glass moon- Review
Craigslist Apartments For Rent Cheap
Craigslist The Big Island
Lesson 10 Homework 5.3
Giant Key Osrs
Https Paperlesspay Talx Com Boydgaming
Gma Deals And Steals December 5 2022
Buff Streams .Io
Jikatabi Thothub
Saxies Lake Worth
Cincinnati Adult Search
Ups Open Today Near Me
What You Need to Know About County Jails
Msu Ro
Savage Model 110 Serial Number Lookup
20 Cozy and Creative Fall Front Porch Ideas to Welcome the Season in Style
Naughty Neighbor Tumblr
Rugged Gentleman Barber Shop Martinsburg Wv
Kate Spade OUTLET • bis 70%* im Sale | Outletcity Metzingen
T33N Leaks 5 17
Cheap Motorcycles For Sale Under 1000 Craigslist Near Me
Dovob222
Xxc Renegade 1000 Xxc Price In India Price
Coleman Funeral Home Olive Branch Ms Obituaries
Sheetz Unlimited Drinks Ending
Emma D'arcy Deepfake
What Is My Walmart Store Number
Work with us | Pirelli
85085 1" Drive Electronic Torque Wrench 150-1000 ft/lbs. - Gearwrench
Marissa.munoz17
Leesburg Regional Medical Center Medical Records
Missing 2023 Showtimes Near Golden Ticket Cinemas Dubois 5
Chevalier Showtimes Near Island 16 Cinema De Lux
Fade En V Pelo Corto
Fallen Avatar Mythic Solo
Seats 3D Ubs Arena
Franchisee Training & Support | Papa Johns Pizza Franchise UK
Unfall mit Ikarus C42: Gefangen in der Umkehr-Falle
Walgreens Pharmacy On Jennings Station Road
Secondary Math 2 Module 3 Answers
Star News Mugshots
More massage parlors shut down by Roswell Police after ordinance violations
Luoghi MA.R.C.I.: Norma e Classificazione
Portmanteau Structure Built With Cans
Fayetteville Arkansas Craigslist
Yi Asian Chinese Union
Black Adam Showtimes Near Grand 18 - Winston-Salem
Dominos Nijmegen Daalseweg
Lizzyboat African Market
Latest Posts
Article information

Author: Barbera Armstrong

Last Updated:

Views: 6077

Rating: 4.9 / 5 (59 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Barbera Armstrong

Birthday: 1992-09-12

Address: Suite 993 99852 Daugherty Causeway, Ritchiehaven, VT 49630

Phone: +5026838435397

Job: National Engineer

Hobby: Listening to music, Board games, Photography, Ice skating, LARPing, Kite flying, Rugby

Introduction: My name is Barbera Armstrong, I am a lovely, delightful, cooperative, funny, enchanting, vivacious, tender person who loves writing and wants to share my knowledge and understanding with you.