'Unknown string format: DD/MM/YYYY - HH:MM:SS
I am trying to convert my Date columns of my DataFrame to datetime[ns] which is in the format "%d/%m%Y - %H:%M:%S". I have tried multiple methods like, pd.to_datetime, datetime.strptime, datetime.strftime, etc. But every time its showing the error:
TypeError: Unrecognized value type: <class 'str'> During handling of the above exception, another exception occurred: . . . . . Unknown string format: DD/MM/YYYY - HH:MM:SS.
Date Var1 Var2
0 19/03/2021 - 00:01:00 22.52 0
1 19/03/2021 - 00:16:00 22.93 0
2 19/03/2021 - 00:31:00 22.79 0
3 19/03/2021 - 00:46:00 22.65 0
4 19/03/2021 - 01:01:00 22.34 0
above is the sample of my DataFrame.
Your help will be highly appreciated.
Solution 1:[1]
for given specific example...
It is typo, you need /:
df = pd.DataFrame({'Date':['19/03/2021 - 00:01:00',
'19/03/2021 - 00:16:00', '19/03/2021 - 00:31:00',
'19/03/2021 - 00:46:00', '19/03/2021 - 01:01:00']})
df['Date'] = pd.to_datetime(df['Date'], format="%d/%m/%Y - %H:%M:%S")
^^^
print (df)
Date
0 2021-03-19 00:01:00
1 2021-03-19 00:16:00
2 2021-03-19 00:31:00
3 2021-03-19 00:46:00
4 2021-03-19 01:01:00
in general...
Tell the computer exactly what to do by selecting from strftime() and strptime() Format Codes. All components of date and time have to be matched by a directive %... while all other characters have to be exactly as in the input. The computer cannot guess that you meant a . to be a / for example:
s = "10.14.1986"
dt = datetime.strptime(s, "%m/%d/%Y")
will fail with
ValueError: time data '10.14.1986' does not match format '%m/%d/%Y'
because I used the wrong delimiter, / should be .
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
