Home > Back-end >  Convert pandas timedelta to AM & PM data
Convert pandas timedelta to AM & PM data

Time:06-14

How can we convert the timedelta data in column 'time' to 'time_2' in AM/PM format?

index   time        time_2
0   0 days 05:11:00 5:11 AM
1   0 days 05:12:00 5:12 AM
2   0 days 05:13:00 5:13 AM
3   0 days 05:14:00 5:14 AM
4   0 days 05:15:00 5:15 AM
5   0 days 05:16:00 5:16 AM
6   0 days 15:17:00 3:17 PM
7   0 days 15:18:00 3:18 PM
8   0 days 15:19:00 3:19 PM
9   0 days 15:20:00 3:20 PM

CodePudding user response:

You can add (some day), then strftime:

df['time'].add(pd.Timestamp.now().normalize()).dt.strftime("%I:%M %p")

Output:

0    05:11 AM
1    05:12 AM
2    05:13 AM
3    05:14 AM
4    05:15 AM
5    05:16 AM
6    03:17 PM
7    03:18 PM
8    03:19 PM
9    03:20 PM
Name: time, dtype: object

Note: You may need to watch out for day-light saving time.

CodePudding user response:

I think this is what you want:

df.time = pd.to_datetime(df.time, format='%H:%M:%S')
df['time_2'] = df.time.dt.strftime('%I:%M %p')
  • Related