Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert numpy array full of time deltas to hours

I have a numpy array full of timedeltas I want to be able to convert them to hours.

print(times_arr)

array([datetime.timedelta(seconds=28800),
       datetime.timedelta(seconds=30600),
       datetime.timedelta(seconds=23400),
       datetime.timedelta(seconds=27000),
       datetime.timedelta(seconds=23400),
       datetime.timedelta(seconds=23400),
       datetime.timedelta(seconds=30600),
       datetime.timedelta(seconds=23400),
       datetime.timedelta(seconds=27000),
       datetime.timedelta(seconds=23400),
       datetime.timedelta(seconds=30600),
       datetime.timedelta(seconds=27000),
       datetime.timedelta(seconds=23400),
       datetime.timedelta(seconds=23400),
       datetime.timedelta(seconds=30600),
       datetime.timedelta(seconds=28800),
       datetime.timedelta(seconds=23400)])

Does anyone know how I can convert this array to hours so array[(8, 8.56 etc..

I have tried everything I know how. I am new to python. Thanks

like image 256
Oliver Wright Avatar asked Dec 05 '25 16:12

Oliver Wright


2 Answers

Convert to timedelta64[m] dtype, then go from there:

arr.astype('timedelta64[m]').astype(int) / 60
# array([8. , 8.5, 6.5, 7.5, 6.5, 6.5, 8.5, 6.5, 7.5, 6.5, 8.5, 7.5, 6.5,
#        6.5, 8.5, 8. , 6.5])
like image 65
cs95 Avatar answered Dec 08 '25 05:12

cs95


Use arr.astype('timedelta64[s]').astype("int64")/3600 instead of arr.astype('timedelta64[m]').astype(int) / 60 which will cause "loss" of seconds.

like image 23
Ken T Avatar answered Dec 08 '25 04:12

Ken T



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!