python - 如何计算 Pandas 中每月分成几天的两个日期之间的天数

标签 python pandas datetime

我想从“B”中的日期中减去“A”中的日期,并获得日期之间每个月的天数差:

df
      A        B
 2014-01-01  2014-02-28 
 2014-02-03  2014-03-01

df['A'] = pd.to_datetime(df['A'])
df['B'] = pd.to_datetime(df['B'])
#df['A'] - df['B']

Desired Output:
=================
01(Jan)    02(Feb)      03(Mar)
================================
31days     28days       0days
0days      26days       1day     

如何使用 pandas 实现这一点?

最佳答案

有趣的问题,感谢分享。这里介绍的基本思想是构建一个可以在开始日期和结束日期之间迭代的函数,并返回一个包含年/月键和该月天数值的字典。

代码:

import calendar
import datetime as dt

def year_month(date):
    """ return year/month tuple from date """
    return date.year, date.month

def next_year_month(date):
    """ given a year/month tuple, return the next year/month """
    if date[1] == 12:
        return date[0] + 1, 1
    else:
        return date[0], date[1] + 1

def days_per_month(start_date, end_date):
    """ return dict keyed with year/month tuples and valued with days in month """
    assert isinstance(start_date, (dt.datetime, dt.date))
    assert isinstance(end_date, (dt.datetime, dt.date))

    start = year_month(start_date)
    end = year_month(end_date)
    days_in_month = (
        calendar.monthrange(*start)[1] - start_date.day + 1)

    result = {}
    while start != end:
        result[start] = days_in_month
        start = next_year_month(start)
        days_in_month = calendar.monthrange(*start)[1]
    result[end] = (
        end_date.day - calendar.monthrange(*end)[1] + days_in_month)
    return result

测试代码:

import pandas as pd
data = [x.strip().split() for x in """
        A          B
    2014-01-01  2014-02-28
    2014-02-03  2014-03-01
    2014-02-03  2014-02-05
""".split('\n')[1:-1]]
df = pd.DataFrame(data=data[1:], columns=data[0])
df['A'] = pd.to_datetime(df['A'])
df['B'] = pd.to_datetime(df['B'])

result = pd.DataFrame.from_records(
    (days_per_month(a, b) for a, b in zip(df['A'], df['B']))
).fillna(0).astype(int)

print(result)

结果:

   (2014, 1)  (2014, 2)  (2014, 3)
0         31         28          0
1          0         26          1
2          0          3          0

关于python - 如何计算 Pandas 中每月分成几天的两个日期之间的天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42465726/

相关文章:

Python any() - 除了 0 之外每个数字都返回 true 吗?

python - 如何将多列乘以另一列 Pandas

php - 字符串转换为日期时间返回错误的日期

javascript - 获取当前日期,将字符串解析为日期并比较日期

python - 使用 NumPy asarray 方法将列表转换为数组

python - Django 获取所有用户

python - 是否有任何选项可以使用或运算符在同一 if 语句中将变量与数字和字符串进行比较?

python - pandas DataFrame 多个子串匹配,还将一行的特定匹配子串放入新列

python - 映射到 pandas 中的子字符串键

Python 日期时间减法 - 结果错误?