I have a datetime column in my csv file that has the format mm/dd/yyyy hh:mm:ss
TimeCreated |
---|
7/20/2020 7:59:48 AM |
7/20/2020 8:53:32 AM |
7/20/2020 8:53:33 AM |
7/20/2020 4:32:04 PM |
7/21/2020 8:54:50 AM |
7/21/2020 8:55:31 AM |
7/21/2020 1:42:26 PM |
7/21/2020 1:42:26 PM |
I want to convert this so that it reads in the format dd/mm/yyyy hh:mm:ss The Python I am using to try and achieve this:
import pandas as pd
import datetime
df = pd.read_csv('sample.csv')
def format(val):
df = pd.to_datetime(val, errors='coerce', cache=False).strftime('%m/%d/%Y %H:%M:%S')
try:
date_time_obj = datetime.datetime.strptime(df, '%d/%m/%Y %H:%M:%S')
except:
date_time_obj = datetime.datetime.strptime(df, '%m/%d/%Y %H:%M:%S')
return date_time_obj.date()
# Saving the changes to the same column.
df['TimeCreated'] = df['TimeCreated'].apply(lambda x: format(x))
df.to_csv(f'output.csv', index=False, date_format='%s')
This works to produce my new column like:
TimeCreated |
---|
20/07/2020 |
20/07/2020 |
20/07/2020 |
20/07/2020 |
21/07/2020 |
21/07/2020 |
21/07/2020 |
21/07/2020 |
However I cannot see the hours, minutes and seconds.
I am new to using the datetime library so any help is much appreciated.