I’ve a data frame contains a column (Start Shift) and it has different data types (Datetime/string), What i need is to change the datetime format to be time format only and keep the string without any change, i used the below code to solve this issue but i can’t find a way to apply this change in the data frame as when i trying to load the data frame after this change i found nothing has been changed.
The code that i used:-
JavaScript
x
9
1
df=pd.read_excel(r"C:UsersMahmoud.BaderDesktopFP Attendance V1.6 Apr 22.xlsx","Attendance").fillna("")
2
3
for i in df['Start Shift']:
4
try:
5
if i.isalpha():
6
i
7
except:
8
i.strftime('%H:%M %p')
9
The Data Frame is:-
JavaScript
1
12
12
1
Department Start Shift
2
Accommodation Annual
3
Accommodation OFF Day
4
Accommodation 2022-04-01 12:00:00
5
Accommodation 2022-04-01 09:00:00
6
Accommodation 2022-04-01 10:00:00
7
Complaints OFF Day
8
Complaints 2022-04-29 07:00:00
9
Complaints 2022-04-29 08:00:00
10
Complaints 2022-04-30 07:00:00
11
Complaints 2022-04-30 08:00:00
12
The Data Frame that i expected to found:-
JavaScript
1
12
12
1
Department Start Shift
2
Accommodation Annual
3
Accommodation OFF Day
4
Accommodation 12:00 PM
5
Accommodation 09:00 AM
6
Accommodation 10:00 AM
7
Complaints OFF Day
8
Complaints 07:00 AM
9
Complaints 08:00 AM
10
Complaints 07:00 AM
11
Complaints 08:00 AM
12
Advertisement
Answer
You can try to cast the dates into datetime
first:
JavaScript
1
9
1
# cast column 'Start Shift' to datetime
2
df['Start Shift Formatted'] = pd.to_datetime(df['Start Shift'], format='%Y-%m-%d %H:%M:%S', errors='coerce')
3
# convert into requested time format
4
df['Start Shift Formatted'] = df['Start Shift Formatted'].dt.strftime('%I:%M %p')
5
# overwrite old time format
6
df['Start Shift'] = df['Start Shift'].mask(df['Start Shift Formatted'].notna(), df['Start Shift Formatted'])
7
# drop column 'Start Shift Formatted' as it is no longer needed
8
df.drop('Start Shift Formatted', axis=1, inplace=True)
9
Update: This can be applied to multiple columns using the following function:
JavaScript
1
11
11
1
def format_time(x):
2
x_temp = pd.to_datetime(x, format='%Y-%m-%d %H:%M:%S', errors='coerce')
3
x_temp = x_temp.dt.strftime('%I:%M %p')
4
x = x.mask(x_temp.notna(), x_temp)
5
6
return x
7
8
df.loc[:, ['Start Shift','End Shift','Login Time','Logout time']] = df[
9
['Start Shift','End Shift','Login Time','Logout time']
10
].apply(format_time)
11