【问题标题】:Trying to find the missing dates between the range of dates试图找到日期范围之间的缺失日期
【发布时间】:2021-11-30 20:52:24
【问题描述】:

我有一个每周日期作为范围,我想计算该期间之间的缺失日期。日期范围是从 1992 年开始的,所以不能手动输入。日期数据在以下格式的 excel 中可用。

1992-12-18

1992-12-25

1993-01-08

当我通过将前两个日期作为开始和结束来运行以下代码时,我得到了正确的结果。

我尝试将此日期转换为 pd.to_datetime(dates[0]).dt.date 还有 pd.to_datetime(dates[0]).dt.normalize()

import datetime
import pandas as pd
data = pd.read_excel("-------------------",header=None)
for t in data[0]:
    start = datetime.datetime.strptime(str(t), %Y-%m-%d %H:%M:%S")
    end = datetime.datetime.strptime(str(t+1), %Y-%m-%d %H:%M:%S")
    date = (start + datetime.timedelta(days = x) for x in range(0,(end- 
start).days))
for data_ob in date:
    print(data_ob.strftime("%Y-%m-%d"))

ValueError: 不能在没有频率的情况下将整数值添加到时间戳

【问题讨论】:

标签: python-3.x


【解决方案1】:

这是一种使用datetimecalendar 模块获取两个日期范围之间所有缺失日期的解决方案,不返回重复日期,也不返回输入日期列表中的任何日期:

from datetime import datetime
from calendar import monthrange
from pprint import pprint


def get_missing_dates(dates: list) -> list:
    """Find missing dates"""
    out = set()
    for date in dates:
        _date = datetime.strptime(date, '%Y-%m-%d')
        year, month, day = _date.year, _date.month, _date.day
        for missing in range(*monthrange(year, month)):
            to_add = datetime(year, month, missing).strftime('%Y-%m-%d')
            if date not in out and not day == missing and to_add not in dates:
                out.add(to_add)
    return sorted(list(out))


dates = ['1992-12-18', '1992-12-25']
missing_dates = get_missing_dates(dates)
pprint(missing_dates)

输出:

['1992-12-01',
 '1992-12-02',
 '1992-12-03',
 '1992-12-04',
 '1992-12-05',
 '1992-12-06',
 '1992-12-07',
 '1992-12-08',
 '1992-12-09',
 '1992-12-10',
 '1992-12-11',
 '1992-12-12',
 '1992-12-13',
 '1992-12-14',
 '1992-12-15',
 '1992-12-16',
 '1992-12-17',
 '1992-12-19',
 '1992-12-20',
 '1992-12-21',
 '1992-12-22',
 '1992-12-23',
 '1992-12-24',
 '1992-12-26',
 '1992-12-27',
 '1992-12-28',
 '1992-12-29',
 '1992-12-30']

【讨论】:

  • 如何将日期从 excel 到日期,因为存在格式问题,即 Timestamp('1992-12-29' 00:00:00)
猜你喜欢
  • 1970-01-01
  • 2021-08-15
  • 2021-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多