import pandas as pd from datetime import datetime Load the CSV file filepath =…
- User
import pandas as pd from datetime import datetime
Load the CSV file
file_path = 'XKrishnagiriTownList.csv' # Update this path df = pd.read_csv(file_path)
Define a function to convert the "From" date to the desired format
def convert_date_to_list_format(date_str): try: # Parse the date string to a datetime object date_obj = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S') # Convert to the desired format "Month/Day" return f"{date_obj.month} / {date_obj.day}" except ValueError: # If the date is not in the expected format, return it as is return date_str
Apply the function to the "From" column
df['From'] = df['From'].apply(convert_date_to_list_format)
Save the modified DataFrame to a new CSV file
output_file_path = 'MettupalayamTownList-complet.csv' # Update this path df.to_csv(output_file_path, index=False)
Print the updated DataFrame
print(df) add above code csv file utf 8 encoding converter python code
- Assistant
To ensure the CSV file is read and written using UTF-8 encoding, you can specify the encoding parameter when using
pd.read_csv()anddf.to_csv(). Here's how you can incorporate UTF-8 encoding into your existing Python script:import pandas as pd from datetime import datetime # Load the CSV file with UTF-8 encoding file_path = 'XKrishnagiriTownList.csv' # Update this path df = pd.read_csv(file_path, encoding='utf-8') # Define a function to convert the "From" date to the desired format def convert_date_to_list_format(date_str): try: # Parse the date string to a datetime object date_obj = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S') # Convert to the desired format "Month/Day" return f"{date_obj.month} / {date_obj.day}" except ValueError: # If the date is not in the expected format, return it as is return date_str # Apply the function to the "From" column df['From'] = df['From'].apply(convert_date_to_list_format) # Save the modified DataFrame to a new CSV file with UTF-8 encoding output_file_path = 'MettupalayamTownList-complet.csv' # Update this path df.to_csv(output_file_path, index=False, encoding='utf-8') # Print the updated DataFrame print(df)