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:
How to get the difference in weeks, not nanoseconds, rounded up to a whole value?
How to get value out of 'numpy.timedelta64' object?
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.
Use df. dates1-df. dates2 to find the difference between the two dates and then convert the result in the form of months.
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.
Use the relativedelta. months + relativedelta. years * 12 formula to get the total months between two dates.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With