AttributeError: Can only use .dt accessor with datetimelike values when use dataframe to deal time

The data in test.csv likes this:

device_id,upload_time
id1,2020-06-01 07:46:30+00:00
id2,2020-06-05 16:04:32+00:00

When I use this code to add column of dataframe.

import pandas as pd

df = pd.read_csv(r'E:/test.csv',parse_dates=[1], encoding='utf-8')
df['new_upload_time'] = df['upload_time'] + pd.Timedelta(hours=8) #add 8 hours
df['new_upload_time'] = df['new_upload_time'].dt.strftime('%Y-%m-%d %H:%M:%S')
df['upload_time_year_month'] = df['new_upload_time'].dt.strftime('%Y%m')
df.to_csv(r'E:/result.csv', index=False, mode='w', header=True)

The error message is:

AttributeError: Can only use .dt accessor with datetimelike values

How to fix it?



Read more here: https://stackoverflow.com/questions/64399796/attributeerror-can-only-use-dt-accessor-with-datetimelike-values-when-use-data

Content Attribution

This content was originally published by CR7 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: