AttributeError: Can only use .dt accessor with datetimelike values

avatar
Borislav Hadzhiev

Last updated: Apr 11, 2024
4 min

banner

# 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 datetimelike values" occurs when you try to access the .dt attribute on a non-datetime value.

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

Here is an example of how the error occurs.

main.py
import pandas as pd df = 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)

attribute error can only use dt accessor with datetimelike values

We tried to access the dt attribute on the date column, however, the values in the column are of type object, 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 the pandas.to_datetime() method to convert the values in the column to datetime objects.

main.py
import pandas as pd df = 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
0 2023 1 2023 2 2021 3 2022 Name: date, dtype: int32

using to datetime method to solve the error

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 a DataFrame 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 the method.

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

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

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

main.py
import pandas as pd df = 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)

using to datetime method to solve the error

The code for this article is available on GitHub

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

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

# Solving the error by explicitly setting the format

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

Here is an example.

main.py
import pandas as pd df = 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)

setting the format explicitly to solve the error

The code for this article is available on GitHub

Running the code sample produces the following output.

shell
0 2023 1 2023 2 2021 Name: date, dtype: int32

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

main.py
import pandas as pd df = 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)

using correct format string

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 the strings in the column.

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

main.py
import pandas as pd df = 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 2022 print(df)

create new column that stores specific date component

The code for this article is available on GitHub

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

You can also check the following article on 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 the pandas.read_csv() method, you have to supply the parse_dates argument.

main.py
import pandas as pd file_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-24 print(df) print('-' * 50) print(df['date'].dtype) # datetime64[ns] print('-' * 50) # 0 2023 # 1 2023 # 2 2021 # Name: date, dtype: int32 print(df['date'].dt.year)

solve error when reading csv file

The code for this article is available on GitHub

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

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

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

# Additional Resources

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

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev