1

I am trying to convert my date column called df['CO date'] which shows in this format 3/02/21 meaning date/month/year, the problem arises when I parse it and then pass it to string, like this.

df['CO date'] = pd.to_datetime(df['CO date']).dt.strftime("%d/%m/%y")

for some reason after I converted from datetime to string with the shown format it returns my date in an american format like 02/03/21 , I don't understand why this happens, the only thing I can think of is that Python only has the string format %d which shows the days as 01,02,03,04,etc where as the date on my df originally is day "3" (non-padding zero).

Does anybody know how can I solve this problem?.

Many thanks in advance

2 Answers 2

3

Your formatting looks right. The only way you get that result, is your data frame contains wrong or corrupted data. You can make a sanity check by:

pd.to_datetime("2021-03-02").strftime("%d/%m/%y")
>>>
'02/03/21'

I think you are converting with wrong format in the beginning at pd.to_datetime(df['CO date']) part. If you know exact format you should use format in pd.to_datetime like:

pd.to_datetime("2021-02-03", format="%Y-%d-%m").strftime("%d/%m/%y")
>>>
'02/03/21'
Sign up to request clarification or add additional context in comments.

Comments

0

output date in a try and catch block and see if you can get the dataframe column with the invalid date to try an error. Check for ranges for day and month and year and custom throw and error if exceeded.

 print(date.day)
 print(date.month)
 print(date.year)

 def date_check(date):
     try:
          datetime.strptime(date, '%d/%m/%Y')
          return True
     except ValueError:
          return False

or

  if pd.to_datetime(df['date'], format='%d-%b-%Y', errors='coerce').notnull().all():

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.