Coding Wheel
Coding Wheel

Reputation: 1

Convert date column (string) to datetime and match the format

I'm trying to covert the next date column (str) to datetime64 and say that format doesn't match, can anyone help me pleas :)

Column:

df["Date"]

0 15/7/21 ... 2541 13/9/21 dtype: object

What I try:

pd.to_datetime(df["Date"], format = "%d/%m/%Y")

ValueError: time data '15/7/21' does not match format '%d/%m/%Y' (match)

I also try:

pd.to_datetime(df["Date"].astype("datetime64"), format='%d/%m/%Y')

And it convert it as datetime but there is some date the day is in the month.

Anyone know what to do ?

Upvotes: 0

Views: 177

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 178197

%Y expects a 4-digit year. Use %y for a 2-digit year (See the docs):

>>> import pandas as pd
>>> df = pd.DataFrame({'Date':['15/7/21','13/9/21']})
>>> df['Date']
0    15/7/21
1    13/9/21
Name: Date, dtype: object
>>> pd.to_datetime(df['Date'].astype('datetime64'),format='%d/%m/%y')
0   2021-07-15
1   2021-09-13
Name: Date, dtype: datetime64[ns]

Note that pandas is pretty good at guessing the format:

>>> pd.to_datetime(df['Date'])
0   2021-07-15
1   2021-09-13

Upvotes: 1

Related Questions