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
Visit Harlem With Our Visitors Guide
Book Review: When His Eyes Opened Novel by Simple Silence - Billionaire
9.4: Resonance Lewis Structures
Ron Martin Realty Cam
55Th And Kedzie Elite Staffing
Froedtert Billing Phone Number
Euro (EUR), aktuální kurzy měn
Www.politicser.com Pepperboy News
Math Playground Protractor
P2P4U Net Soccer
Flat Twist Near Me
Heska Ulite
Slay The Spire Red Mask
Espn Expert Picks Week 2
You can put a price tag on the value of a personal finance education: $100,000
Audrey Boustani Age
Busby, FM - Demu 1-3 - The Demu Trilogy - PDF Free Download
Daily Voice Tarrytown
Abortion Bans Have Delayed Emergency Medical Care. In Georgia, Experts Say This Mother’s Death Was Preventable.
Christina Steele And Nathaniel Hadley Novel
What Channel Is Court Tv On Verizon Fios
Busted Mcpherson Newspaper
Craigslist Org Appleton Wi
LCS Saturday: Both Phillies and Astros one game from World Series
Delectable Birthday Dyes
Wrights Camper & Auto Sales Llc
NV Energy issues outage watch for South Carson City, Genoa and Glenbrook
Yayo - RimWorld Wiki
Turns As A Jetliner Crossword Clue
Isablove
Ryujinx Firmware 15
The Posturepedic Difference | Sealy New Zealand
Autotrader Bmw X5
6143 N Fresno St
Pokemon Reborn Locations
Taylor University Baseball Roster
Metro Pcs Forest City Iowa
Xxn Abbreviation List 2023
How to Get a Better Signal on Your iPhone or Android Smartphone
Ukraine-Krieg - Militärexperte: "Momentum bei den Russen"
Tableaux, mobilier et objets d'art
Az Unblocked Games: Complete with ease | airSlate SignNow
844 386 9815
Jammiah Broomfield Ig
Cult Collectibles - True Crime, Cults, and Murderabilia
New Starfield Deep-Dive Reveals How Shattered Space DLC Will Finally Fix The Game's Biggest Combat Flaw
Aznchikz
Minecraft: Piglin Trade List (What Can You Get & How)
Assignation en paiement ou injonction de payer ?
Powah: Automating the Energizing Orb - EnigmaticaModpacks/Enigmatica6 GitHub Wiki
David Turner Evangelist Net Worth
Cbs Scores Mlb
Latest Posts
Article information

Author: Terence Hammes MD

Last Updated:

Views: 6548

Rating: 4.9 / 5 (69 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Terence Hammes MD

Birthday: 1992-04-11

Address: Suite 408 9446 Mercy Mews, West Roxie, CT 04904

Phone: +50312511349175

Job: Product Consulting Liaison

Hobby: Jogging, Motor sports, Nordic skating, Jigsaw puzzles, Bird watching, Nordic skating, Sculpting

Introduction: My name is Terence Hammes MD, I am a inexpensive, energetic, jolly, faithful, cheerful, proud, rich person who loves writing and wants to share my knowledge and understanding with you.