I'm trying to reformat a datetime pattern on csv's files:
Original date format:
DAY/MONTH/YEAR
Expected Result:
YEAR/MONTH/DAY
rows = df['clock_now']
is:
22/05/2022 12:16
22/05/2022 12:20
22/05/2022 12:21
22/05/2022 12:44
22/05/2022 12:47
22/05/2022 12:47
22/05/2022 12:51
Here is my complete code:
import pandas as pd
import datetime
filials= [
'base.csv',
'max.csv'
]
for filial in filials:
df = pd.read_csv(filial)
rows = df['clock_now']
for row in rows:
change_format = datetime.datetime.strptime(row, '%d/%m/%Y %H:%M')
final_format = change_format.strftime('%Y/%m/%d %H:%M')
df.loc[df['clock_now'] == row, 'clock_now'] = final_format
df.to_csv(filial, index=False)
Returns this error saying format error in one of the values, but there is no '2022/05/22 12:47'
value in rows = df['clock_now']
.
change_format = datetime.datetime.strptime(row, '%d/%m/%Y %H:%M')
File "C:\Users\Computador\AppData\Local\Programs\Python\Python310\lib\_strptime.py", line 568, in _strptime_datetime
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
File "C:\Users\Computador\AppData\Local\Programs\Python\Python310\lib\_strptime.py", line 349, in _strptime
raise ValueError("time data %r does not match format %r" %
ValueError: time data '2022/05/22 12:47' does not match format '%d/%m/%Y %H:%M'
What am I missing out?
CodePudding user response:
You can try this,
dt_rows = pd.to_datetime(rows)
dt_rows = pd.Series(map(lambda dt:dt.strftime("%Y/%m/%d %H:%M"), dt_rows))
Output -
0 2022/05/22 12:20
1 2022/05/22 12:21
2 2022/05/22 12:44
3 2022/05/22 12:47
4 2022/05/22 12:47
5 2022/05/22 12:51
dtype: object