【问题标题】:How to calculate number of Mondays left in a month with Python如何使用 Python 计算一个月内剩余的星期一数
【发布时间】:2018-04-06 17:51:45
【问题描述】:

我正在用 Python 构建一个预测模型,需要计算一个月中每一天的剩余天数。例如,在 2017 年 10 月 25 日,当月没有剩余的周三,周四、周五、周六、周日、周一和周二还有 1 个。

我可以通过以下方式在 R 中实现相同的结果:

first <- as.Date(cut(Sys.Date(), "month"))
last <- as.Date(cut(first + 31, "month")) - 1
sum(format(seq(Sys.Date(), last, "day"), "%w") == 0) -> Sunday

我正在尝试编辑以下代码块,该代码块最初是为了我的目的而计算一个月中的工作日,但不确定我是否走在正确的轨道上

import calendar

weekday_count = 0
cal = calendar.Calendar()

for week in cal.monthdayscalendar(2013, 8):
for i, day in enumerate(week):
    # not this month's day or a weekend
    if day == 0 or i >= 5:
        continue
    # or some other control if desired...
    weekday_count += 1

print(weekday_count)

【问题讨论】:

  • 你的代码在哪里?
  • 请发布您的代码
  • I'm able to achieve the same result in R with: > 那你为什么把它标记为 Python 问题??
  • 因为我需要在 Python 中这样做
  • @kame 很抱歉省略了我的原始代码 - 我已经包含了到目前为止我正在使用的内容,以及 R 的示例(如果这有助于进一步解释我的解决方案)米找)

标签: python


【解决方案1】:

您可能希望以此为起点。它将根据您选择的日、月、年计算剩余的星期一数。

from datetime import datetime, timedelta


# Monday = 0
def get_remaining_mondays(year, month, day):
    count = 0
    try:
        d = datetime(year, month, day)
        wday = d.weekday()

        d += timedelta(days=7 - wday)
        while d.month == month:
            count += 1
            d += timedelta(days=7)
    except ValueError as v:
        return v

    return count


print(get_remaining_mondays(2017, 11, 7))

【讨论】:

    猜你喜欢
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    • 2021-02-18
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多