DDM
DDM

Reputation: 323

Pandas Change time string in a column to 24 hour time format

hi all I have a column df['TimeEnd'] where these are the string values and I am trying to convert them to 24 hr time format. What will be the easiest way to do it?

Time End  Counts
1058PM    56
0501PM    26
1145PM    24
1125PM    24
0605PM    20

Upvotes: 0

Views: 898

Answers (1)

jezrael
jezrael

Reputation: 862661

Use to_datetime with Series.dt.strftime:

df['Time End'] = pd.to_datetime(df['Time End'], format='%I%M%p').dt.strftime('%H:%M')
print (df)
  Time End  Counts
0    22:58      56
1    17:01      26
2    23:45      24
3    23:25      24
4    18:05      20

If there are wrong values like 1300PM add errors='coerce' for misisng values if no match, convert to format with H (24H format) instead I (12H format) and repalce possible misisng values by parsed datetimes d2:

print (df)
  Time End  Counts
0   1300PM      56
1   0501PM      26
2   1145PM      24
3   1125PM      24
4   0605PM      20

d1 = pd.to_datetime(df['Time End'], format='%I%M%p', errors='coerce')
d2 = pd.to_datetime(df['Time End'], format='%H%M%p', errors='coerce')

df['Time End'] = d1.fillna(d2).dt.strftime('%H:%M')


print (df)
  Time End  Counts
0    13:00      56
1    17:01      26
2    23:45      24
3    23:25      24
4    18:05      20

Upvotes: 2

Related Questions