In a similar vein to this question, I have a numpy.timedelta64
column in a pandas DataFrame. As per this answer to the aforementioned question, there is a function pandas.tslib.repr_timedelta64
which nicely displays a timedelta in days, hours:minutes:seconds. I would like to format them only in days and hours.
So what I've got is the following:
def silly_format(hours):
(days, hours) = divmod(hours, 24)
if days > 0 and hours > 0:
str_time = "{0:.0f} d, {1:.0f} h".format(days, hours)
elif days > 0:
str_time = "{0:.0f} d".format(days)
else:
str_time = "{0:.0f} h".format(hours)
return str_time
df["time"].astype("timedelta64[h]").map(silly_format)
which gets me the desired output but I was wondering whether there is a function in numpy
or pandas
similar to datetime.strftime
that can format numpy.timedelta64
according to some format string provided?
I tried to adapt @Jeff's solution further but it is way slower than my answer. Here it is:
days = time_delta.astype("timedelta64[D]").astype(int)
hours = time_delta.astype("timedelta64[h]").astype(int) % 24
result = days.astype(str)
mask = (days > 0) & (hours > 0)
result[mask] = days.astype(str) + ' d, ' + hours.astype(str) + ' h'
result[(hours > 0) & ~mask] = hours.astype(str) + ' h'
result[(days > 0) & ~mask] = days.astype(str) + ' d'