简体   繁体   中英

Python Pandas: differences between two dates in weeks?

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?

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 .

You can use pandas.Timedelta as well:

import pandas as pd

def diff(start, end):
    days = pd.to_datetime(end) - pd.to_datetime(start)
    week = int(pd.Timedelta(days).days / 7)
    remainder = pd.Timedelta(days).days % 7
    return str(week) + ' weeks and ' + str(remainder) + ' days'

print(diff("2019-06-10","2019-07-11"))

Output:
4 weeks and 3 days

Here's a simple fix:

def diff(start, end):
    x = millis(end) - millis(start)
    return np.ceil(x.astype(int) / (7*86400*1e9))

The main thing is to remove the units (nanoseconds) before operating on it.

PS: Consider not calling your function millis() when it does not return milliseconds.

jezrael's answer threw an error for me so here's an alternate solution (in case you also got an error when trying it)

import numpy as np
import pandas as pd
def diff(start, end):
    x = pd.to_datetime(end) - pd.to_datetime(start)
    return (x).apply(lambda x: x/np.timedelta64(1,'W')).astype(int)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM