0

The delta_s function calculates the difference of time between 2 dates in the dates with seconds. Then the average median and max values for the differences is calculated. I am trying to convert the times in seconds for average median and max values but it does not work. i want to convert it in the form of x days x hours x minutes x seconds.

Code:

import numpy as np

dates= np.array(['2017-09-15 07:11:00' ,'2017-09-15 11:25:30', '2017-09-15 12:11:10', '2021-04-07 22:43:12', '2021-04-08 00:49:18'], 
                dtype="datetime64[ns]")

delta_s = np.diff(dates) // 1e9 # nanoseconds to seconds
delta_s = delta_s.astype(np.float64)

delta_avg = np.average(delta_s)
delta_median= np.median(delta_s)
delta_max = np.max(delta_s)
delta_max_index= np.argmax(delta_s)
1
  • what specifically "does not work"? Commented May 29, 2021 at 8:44

1 Answer 1

1

The line delta_s = np.diff(dates) // 1e9 does not actually convert nanoseconds to seconds. It simply divides 1e9 to the timedelta object but the time unit is preserved timedelta64[ns].

>>> np.diff(dates)
array([    15270000000000,      2740000000000, 112357922000000000,
            7566000000000], dtype='timedelta64[ns]')
>>> np.diff(dates) // 1e9
array([    15270,      2740, 112357922,      7566],
      dtype='timedelta64[ns]')

This may mess up with any calculations you're doing.

Use

delta_s = np.array([np.timedelta64(td, 's') for td in np.diff(dates) ])

Currently there are no inbuilt functions to format timedelta to strings. However you can use something of this sort.

# Function to convert seconds to Human readable Timedelta string
def seconds_to_tdstring(total_seconds):
    days, remainder = divmod(total_seconds, 60 * 60 * 24)
    hours, remainder = divmod(remainder, 60 * 60)
    minutes, seconds = divmod(remainder, 60)
    return '{:02} Days {:02} Hours {:02} Minutes {:02} Seconds'.format(int(days), int(hours), int(minutes), int(seconds))

print(seconds_to_tdstring(delta_avg))  

Output:
325 Days 04 Hours 24 Minutes 34 Seconds

I have modified the answer from a similar question .

Sign up to request clarification or add additional context in comments.

1 Comment

the list comprehension is not needed; you can simply do delta_s = np.diff(dates).astype('timedelta64[s]')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.