Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to format different data types to a dd/mm/yyyy format in Python

I have an code that I want to change all the date column to a format of dd/mm/yyyy.
All the values passed in the date column are already in this kind of format, even the second value: 01/02/2001, where I want to display as day:01, month: 02 (February), year: 2001.

How can i get my code to change this kind of value?

I searched on Chatgpt, but the code they responded with doesn’t work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My code:

import pandas as pd


data = {
    'Date': ['01/01/01', '01-02-2001', 'March 1rd, 2001'],    
    'Name': ['Ana', 'Bob', 'Carl']
}
df_data = pd.DataFrame(data)

# Change to datetime data type
df_data['Date'] = pd.to_datetime(df_data['Date'])

# Change the Date format to dd/mm/yyyy
df_data['Date'] = df_data['Date'].dt.strftime("%d/%m/%Y")

Output:

         Date  Name
0  01/01/2001   Ana
1  02/01/2001   Bob
2  01/03/2001  Carl

Desired Output:

         Date  Name
0  01/01/2001   Ana
1  01/02/2001   Bob
2  01/03/2001  Carl

ChatGpt response:

import pandas as pd

# Create a sample dataframe with dates in different formats
data = {'Date': ['2022-01-01', '01-02-2022', '01/03/2022', '2022/04/01', '01-Apr-2022'], 'Name': ['Ana', 'Bob', 'Carl', 'Dave', 'Emma']}
df = pd.DataFrame(data)

# Define the possible date formats
date_formats = ["%Y-%m-%d", "%d-%m-%Y", "%m/%d/%Y", "%d/%m/%Y", "%d-%b-%Y"]

# Convert the 'Date' column to datetime format
df['Date'] = pd.to_datetime(df['Date'], format=date_formats, errors='coerce')

print(df)

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-1c5d1f56aa15> in <cell line: 11>()
      9 
     10 # Convert the 'Date' column to datetime format
---> 11 df['Date'] = pd.to_datetime(df['Date'], format=date_formats, errors='coerce')
     12 
     13 print(df)

1 frames
/usr/local/lib/python3.9/dist-packages/pandas/core/tools/datetimes.py in _convert_listlike_datetimes(arg, format, name, tz, unit, errors, infer_datetime_format, dayfirst, yearfirst, exact)
    386         # format because this path makes process slower in this
    387         # special case
--> 388         format_is_iso8601 = format_is_iso(format)
    389         if format_is_iso8601:
    390             require_iso8601 = not infer_datetime_format

TypeError: Argument 'f' has incorrect type (expected str, got list)

>Solution :

Add dayfirst=True parameter to to_datetime()

df_data['Date'] = (pd.to_datetime(df_data['Date'], dayfirst=True, errors='coerce')
                     .dt.strftime('%d/%m/%Y')) 
print(df_data)

         Date  Name
0  01/01/2001   Ana
1  01/02/2001   Bob
2  01/03/2001  Carl
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading