0

Column Name: dateAdded

format: 2017-03-03T16:56:05Z

I am trying this code

df = pd.read_csv ('amazon.csv')
df['dateAdded'] = pd.to_datetime(df['dateAdded'], format= '%Y-%d-%mT%H:%M:%S%Z')     

Error:

time data '2017-03-03T16:56:05Z' does not match format '%Y-%d-%mT%H:%M:%S%Z' (match)

hradecek
  • 2,455
  • 2
  • 21
  • 30
  • You just have one too many `%`. No `%` in front of the Z -> `'%Y-%d-%mT%H:%M:%SZ'` (Tested with this sample `df = pd.DataFrame({'dateAdded': ['2017-03-03T16:56:05Z']})`) – Henry Ecker Dec 16 '21 at 22:48

1 Answers1

0

Z, or Military Time is not supported in Datetime. The solution is to either remove the Z or replace it with +00:00. Your code becomes:

df['dateAdded'] = pd.to_datetime(df['dateAdded'].rsplit('Z', 1)[0], format= '%Y-%d-%mT%H:%M:%S')     

Or if you are using a newer version that supports the Military Time then your solution is to simply replace the %Z in your format with %z (small letter).

df['dateAdded'] = pd.to_datetime(df['dateAdded'].rsplit('Z', 1)[0], format= '%Y-%d-%mT%H:%M:%S%z') 

Another (better IMO) approach is to convert the datetime without using pandas.

from datetime import datetime
df['dateAdded'] = datetime.fromisoformat(df['dateAdded'])

though you're going to have to edit the code above to go over the entire column.

thethiny
  • 1,125
  • 1
  • 10
  • 26
  • I have tried that I am still getting error "Series' object has no attribute 'rsplit" – suhaspaunikar Dec 17 '21 at 07:10
  • then make it `str(df['dateAdded']).rsplit` @suhaspaunikar – thethiny Dec 17 '21 at 08:53
  • thanks i wrore df['dateAdded'] = pd.to_datetime(df['dateAdded'], infer_datetime_format=True) df['dateAdded'] = pd.to_datetime(str(df['dateAdded']).rsplit('Z', 1)[0], format= '%Y-%d-%mT%H:%M:%S') and i am getting error ValueError: time data '0 2017-03-03 16:56:05 1 2017-03-03 16:56:05 2 2017-03-03 16:56:05 3 2017-03-03 16:56:05 4 2017-03-03 16:56:05 33330 2017-03-06 14:59:43 33331 2017-03-06 14:59:43 Name: dateAdded, Length: 33332, dtype: datetime64[ns]' does not match format '%Y-%d-%mT%H:%M:%S' (match) – suhaspaunikar Dec 17 '21 at 09:05
  • i am getting error – suhaspaunikar Dec 17 '21 at 09:06