Home > Net >  Control after changing format date Pandas
Control after changing format date Pandas

Time:11-17

I want to control a date after changing date format

df["Date start"] = pd.to_datetime(df["Date start"])
df["Date start"] = df["Date start"].dt.strftime('%d/%m/%Y')
df = df[df["Date start"] > "01/01/2022"]

But I do have an error like this

UserWarning: Parsing '16/04/2012' in DD/MM/YYYY format. Provide format or specify infer_datetime_format=True for consistent parsing.
  df["Date start"] = pd.to_datetime(fd["Date start"],infer_datetime_format=True)

How can I fix it?

Tried all these methods:

df["date start"] = pd.to_datetime(df["date start"], format='%d/%m/%Y', dayfirst=True).dt.strftime('%d/%m/%Y')
df["date start"] = pd.to_datetime(df["date start"], dayfirst=True)
df["date start"] = df["date start"].dt.strftime("%d/%m/%Y")

CodePudding user response:

for date comparison, make the date as yyyy-mm-dd (without or without hyphens). This ensures the dates being compared are in chronological order

when you have day as first in a date when comparing. it will group all months and all year with the day 1, before day 2 and so on

# inline conversion of date to yyyy-mm-dd (default) format and then comparing
# and filtering the result using LOC
df.loc[pd.to_datetime(df["date start"], dayfirst=True) > "2022-01-01"]


  • Related