I have a piece of code that is taking data in a csv and dong some transformation in a data frame. One of the columns in this data frame contains time in a HH:MM
format, however I need the time to return as HH:MM:SS
.
I've tried the following.
CSV/DF example:
Attended Time |
---|
10:01 |
11:40 |
Version 1
df['Attended Time'] = pd.to_timedelta(df['Attended Time'] ':00', df['Attended Time'])
and
Version 2
df['Attended Time'] = pd.to_timedelta(
np.where(df['Attended Time'].str.count(':') == 1, df['Attended Time'] ':00', df['Attended Time']))
V1 does not populate my Attended Time with the seconds and
V2 gives me my result but adds a 0 days to the time? Anyone know why? example 0 days 10:01:00
CodePudding user response:
If you have strings then you could only add :00
df['Attended Time'] = df['Attended Time'] ':00'
If you want datetime.time
objects then
df['Attended Time'] = pd.to_datetime(df['Attended Time']).dt.time
Minimal example:
import pandas as pd
data = {
'A': ['10:00', '12:00', '13:00'],
}
df = pd.DataFrame(data)
df['B'] = df['A'] ':00'
df['C'] = pd.to_datetime(df['A']).dt.time
print(df)
Result:
A B C
0 10:00 10:00:00 10:00:00
1 12:00 12:00:00 12:00:00
2 13:00 13:00:00 13:00:00