# Table of Contents
- AttributeError: Can only use .dt accessor with datetimelike values
- Solving the error by explicitly setting the format
- 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)
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
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 utc
parameter 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)
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)
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)
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)
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)
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