0

I am trying to write a function where it calculates how many seconds are in between each dates interval however I do not know how I can go about it. Here is the code for it:

def days_between(d):
    d = datetime.strptime(d, "%Y-%m-%d %H:%M:%S")

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'])   
days_between(dates)

expected output:

15240, 2740...

2 Answers 2

2

Cast to numpy 's datetime dtype and use np.diff:

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).astype('timedelta64[s]') # nanoseconds to seconds

print(delta_s)
# [    15270      2740 112357922      7566]
Sign up to request clarification or add additional context in comments.

Comments

1
import numpy as np
from datetime import datetime

def days_between(d):
    new_arr = np.append((),())
    k = d[0]
    for i in d:
        m = i
        i = datetime.strptime(i, "%Y-%m-%d %H:%M:%S")        
        k = datetime.strptime(k, "%Y-%m-%d %H:%M:%S")  
        new_arr = np.append(new_arr,i-k)
        k = m

    for i in range(1,len(new_arr)):
        print(int(new_arr[i].total_seconds()),end=", ") 

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'])
days_between(dates)

1 Comment

if you want to use "native Python", have a look at datetime.fromisoformat

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.