How to remove the time from csv file in python

82 Views Asked by At

How to remove the time from the csv file in python

I have a csv file in this format: "SSP_Ac_INVOICE_DISTRIBUTIONS_17022023072701.csv"

I am trying to remove the time which is after2023.my expectation was SSP_Ac_INVOICE_DISTRIBUTIONS_17022023.csv

I tried to use strptime but getting below error:

s = "SSP_AP_INVOICE_DISTRIBUTIONS_17022023072701.csv"

temp = dt.datetime.strptime(SSP_AP_INVOICE_DISTRIBUTIONS_17022023072701, '%d%m%Y') final = temp.strftime('%d-%m-%Y') print(final)

1

There are 1 best solutions below

1
AU_97_CB On

In the strptime function, you are passing the string 'SSP_AP_INVOICE_DISTRIBUTIONS_17022023072701.csv' instead of the variable s. Also, you are using the wrong format string in strptime. Since the date string in your filename is in the format %d%m%Y%H%M%S, you need to include %H%M%S in the format string to parse the time as well. The code should look something like this:

import datetime as dt

filename = "SSP_AP_INVOICE_DISTRIBUTIONS_17022023072701.csv"

# Parse the date from the filename
date_str = filename.split('_')[3]
date = dt.datetime.strptime(date_str, '%d%m%Y%H%M%S')

# Format the date as required
new_filename = f"{filename.split('_')[0]}_{filename.split('_')[1]}_{filename.split('_')[2]}_{date.strftime('%d%m%Y')}.csv"

print(new_filename)

This code first splits the filename by the underscore character to extract the date string, and then uses strptime to parse the date and time. Finally, it formats the new filename using the date and the other parts of the original filename that were not changed.