【发布时间】: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