【问题标题】:Calculate difference in months from timestamps计算时间戳的月差
【发布时间】:2014-08-10 08:46:37
【问题描述】:

假设我有 2 个时间戳

a=Timestamp('1986-03-31 00:00:00', tz=None)
b=Timestamp('1986-04-18 00:00:00', tz=None)

现在,如果我只取差价b-a,我将得到datetime.timedelta(18)

我怎样才能得到月份的差值,即1。不管他们之间有多少实际天数,我都需要month 的差异。有一个函数SAS 正是我需要的,intck('month',a,b)=1。 python 或 pandas/numpy 中是否有任何等价物?

谢谢!

【问题讨论】:

    标签: python datetime numpy pandas


    【解决方案1】:

    我会将这些转换为 pandas Periods 而不是 Timestamps,然后区分这些

    >>> a=Timestamp('1986-03-31 00:00:00', tz=None).to_period(freq='M')
    >>> b=Timestamp('1986-04-18 00:00:00', tz=None).to_period(freq='M')
    >>> b-a
    1L
    

    【讨论】:

      【解决方案2】:

      如果日期实际上是日期时间对象,试试这个:

      b.month - a.month + (b.year - a.year)*12
      

      您需要分别计算年份。

      【讨论】:

        【解决方案3】:

        如果它们不是日期时间对象:

        t0 = '1986-03-31 00:00:00'
        t1 = '1987-12-31 00:00:00'
        
        month0 = int(t0.split("-")[1])
        month1 = int(t1.split("-")[1])
        
        year0 = int(t0.split("-")[0])
        year1 = int(t1.split("-")[0])
        
        monthdif = (year1-year0)*12 + (month1 - month0)
        

        【讨论】:

          【解决方案4】:

          我正在使用这个:

          import pandas as pd
          
          a = pd.to_datetime('1986-03-31 00:00:00', format='%Y-%m-%d %H:%M:%S')
          b = pd.to_datetime('1986-04-18 00:00:00', format='%Y-%m-%d %H:%M:%S')
          
          mdiff = lambda x,y: 12*(x.year-y.year) + (x.month-y.month)
          
          print("Difference between {} and {} is: {} months".format(b,a,mdiff(b,a)))
          

          1986-04-18 00:00:00 和 1986-03-31 00:00:00 之间的差异是:1 个月

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-11-09
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多