gpt4 book ai didi

Python Pandas : differences between two dates in weeks?

转载 作者:行者123 更新时间:2023-12-04 23:16:16 24 4
gpt4 key购买 nike

尝试查找几周内两个日期之间的差异时:

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")

结果,我得到:
Out[15]: numpy.timedelta64(857,'ns')

这显然是错误的。问题:
  • 如何获得以周为单位的差异,而不是以纳秒为单位取整?
  • 如何从“numpy.timedelta64”对象中获取值(value)?
  • 最佳答案

    我认为您可以通过除以numpy标量来转换为int:

    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

    参见 frequency conversion

    关于Python Pandas : differences between two dates in weeks?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41311990/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com