Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas: differences between two dates in weeks?

Tags:

python

pandas

When trying to find differences between two dates in weeks:

import pandas as pd

def diff(start, end):
    x = millis(end) - millis(start)
    return x / (1000 * 60 * 60 * 24 * 7 * 1000)

def millis(s):
    return pd.to_datetime(s).to_datetime64()

diff("2013-06-10","2013-06-16")

As a result I get:

Out[15]: numpy.timedelta64(857,'ns')

Which is obviously wrong. Questions:

  1. How to get the difference in weeks, not nanoseconds, rounded up to a whole value?

  2. How to get value out of 'numpy.timedelta64' object?

like image 654
zork Avatar asked Dec 24 '16 09:12

zork


People also ask

How do I get weeks between two dates in Python?

We will take the absolute value of this by using the abs() function to prevent the negative value. After this, we have to simply divide this value by 7 to get the difference between these two dates in number of weeks. Here we will use '//' (floor division) operator to ignore the float value after division.

How do you take the difference between two dates in pandas?

Use df. dates1-df. dates2 to find the difference between the two dates and then convert the result in the form of months.

How do you subtract days in pandas?

When the function receives the date string it will first use the Pandas to_datetime() function to convert it to a Python datetime and it will then use the timedelta() function to subtract the number of days defined in the days variable.

How do I get the difference between two dates in a month Python?

Use the relativedelta. months + relativedelta. years * 12 formula to get the total months between two dates.


1 Answers

I think you can convert to int by dividing by numpy scalar:

def diff(start, end):
    x = pd.to_datetime(end) - pd.to_datetime(start)
    return int(x / np.timedelta64(1, 'W'))

print (diff("2013-06-10","2013-06-16"))
0
print (diff("2013-06-10","2013-06-26"))
2

See frequency conversion.

like image 51
jezrael Avatar answered Sep 22 '22 12:09

jezrael