0

I am trying to convert string to datetime. The string syntax is 30JUN21.

Code:

df.column = pd.to_datetime(df.column, , format='%d%^b%y')

Error:

ValueError: '%' is a bad directive in format '%d%^b%y'

I am pretty sure this error relates to the caret. I don't know another way around the upper case month abbreviations.

See https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior.

khelwood
  • 55,782
  • 14
  • 81
  • 108

2 Answers2

1

try this:

import pandas as pd

df = pd.DataFrame([("Date1","NewDate")],columns=["30JUN21","30MAR22"])

df.columns = [pd.to_datetime(column, format='%d%b%y') for column in df.columns]
print(df)

output:

  2021-06-30 2022-03-30

0      Date1    NewDate
XxJames07-
  • 1,833
  • 1
  • 4
  • 17
0

This issue is that directives are case sensitive. I received the data in upper case. The following code resolved the issue.

df.column = pd.to_datetime(df.column.title(), format='%d%b%y')
pppery
  • 3,731
  • 22
  • 33
  • 46