Dynamically Convert different Date formats in a file using python

Dynamically Convert different Date formats in a file using python

Today i am going to share one of the realtime project scenario.

User sending two kind of csv files , one file having no date columns, another has different date format columns and want convert as YYYY-MM-DD format. see below scenarios 

Scenarios :  

How to convert different date format to user agreed format

Example source having 3 date columns , each column having different dates format like dd-Mon-YY, Mon-YY, mm/dd/yyyy

Target format is YYYY-MM-DD

What if some file don’t have date columns, without error it should read/process


import pandas as pd
from datetime import datetime
def convert_date(date_str):
    try:
        # List possible date formats to handle different formats
        date_formats = ["%d/%m/%y", "%d-%m-%Y","%d-%b-%Y","%b-%y",'%m/%d/%Y',"%d-%b-%y"]
       
        for date_format in date_formats:
            try:
                return datetime.strptime(date_str, date_format).strftime("%Y-%m-%d")
            except ValueError:
                pass
       
        # If none of the formats match, return the original string
        return date_str
    except Exception as e:
        return date_str

def read_csv(file):
    df = pd.read_csv(file)
    # Iterate through columns and apply date conversion if it's a date column
    for column in df.columns:
        df[column] = df[column].apply(convert_date)
    print( df)
input_csv_file = 'G:\ETL_Automation\data\date.txt'
read_csv(input_csv_file)




Post a Comment

0 Comments