Finding datetime difference between lists in python

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Finding datetime difference between lists in python



I'm new to python. I've looked at previous threads like this and this. I have a Series of dates and times that created this way:


tp1=
for f in files: ### files is the variable that has all the files I need to read in this loop
t=f[-19:-5] ### these characters in the filename correspond to the date and time
tp1.append(datetime.strptime(t,"%Y%m%d%H%M%S"))
time_p1_cr=pd.to_datetime(pd.Series(tp1), format='%Y-%m-%d %H:%M:%S')



tp1 looks like:


[datetime.datetime(2018, 8, 1, 16, 6, 39),

datetime.datetime(2018, 8, 2, 17, 16, 37),

datetime.datetime(2018, 8, 3, 10, 53, 46),

datetime.datetime(2018, 8, 3, 17, 14, 39),

datetime.datetime(2018, 8, 4, 11, 21, 36),

datetime.datetime(2018, 8, 4, 17, 27, 54),



and so on.
time_p1_cr looks like :


0 2018-08-01 16:06:39

1 2018-08-02 17:16:37

2 2018-08-03 10:53:46

3 2018-08-03 17:14:39



and so on. I need to find the successive differences between the elements of the list. I basically need the time difference. I can't do


t2=tp1[1:]
t3=tp1[:-1]
t4=t3-t2



because t2, and t3 are lists and I can't subtract lists.



So, I tried


test1=time_p1_cr[1:]
test2=time_p1_cr[:-1]
test3=test1.subtract(test2)



according to this.
But test3 turns out to be



test3


0 NaT

1 0 days

2 0 days

3 0 days

4 0 days

5 0 days

6 0 days

7 0 days



and so on. How can I get the time difference between the successive elements?




1 Answer
1



You can use a list comprehension to do this. For example:


differences = [t2 - t1 for t1,t2 in zip(time_p1_cr[:-1], time_p1_cr[1:])]



This will give you a list of datetime.timedelta.


datetime.timedelta





That's perfect! Thank you. :-)
– Kaumz
Aug 10 at 17:03







By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS