I have a data frame named 'df' where the column 'A' contains the time from 0 to 1440 minutes in a day. I want to add extra columns having the same time in hhmm format and hh:mm format. How can I do that in python?
Asked
Active
Viewed 313 times
1 Answers
0
You can first convert values to timedeltas:
df = pd.DataFrame({'A':[10,20,1440, 0]})
df['A'] = pd.to_timedelta(df['A'], unit='min')
print (df)
A
0 0 days 00:10:00
1 0 days 00:20:00
2 1 days 00:00:00
3 0 days 00:00:00
For formating use:
def f(x):
ts = x.total_seconds()
hours, remainder = divmod(ts, 3600)
minutes, seconds = divmod(remainder, 60)
return ('{:02d}:{:02d}').format(int(hours), int(minutes))
df['A'] = pd.to_timedelta(df['A'], unit='min').apply(f)
print (df)
A
0 00:10
1 00:20
2 24:00
3 00:00

jezrael
- 822,522
- 95
- 1,334
- 1,252
-
1basically [this](https://stackoverflow.com/q/538666/10197418) - you might want to use an f-string for the better looks (and up-to-date-ness) ;-) – FObersteiner Jun 17 '21 at 06:48