首页 > 解决方案 > 打印从今天开始的日历

问题描述

我想打印当月的日历,但从 python 中的今天开始。有什么办法可以做到这一点吗?我唯一想尝试的是:

import calendar
y = int(input("Input the year : "))
m = int(input("Input the month : "))
d = int (input("Input the day: "))
print(calendar.month(y, m, d))

回想起来这是一个愚蠢的想法,因为它所做的只是:

打印结果

但考虑到我在 python 中的 3 天经验,它似乎很愚蠢,可以工作。

我希望最终结果看起来像这样:

想要的结果

本质上,我希望日历仅显示该月的剩余天数,而不是整个月。

标签: python-3.xcalendar

解决方案


日历方法返回一个字符串。您可以使用传统的字符串操作方法在打印之前修改字符串 - fe 正则表达式替换:

import calendar
import re

y = 2020
m = 5 
d = 15
h = calendar.month(y, m, 3) # 3 is the width of the date column, not the day-date
print(h)
print()

# replace all numbers before your day, take care of either spaces or following \n

for day in range(d):
    # replace numbers at the start of a line
    pattern = rf"\n{day} "
    h = re.sub(pattern, "\n  " if day < 10 else "\n   ", h)
    # replace numbers in the middle of a line
    pattern = rf" {day} "
    h = re.sub(pattern, "   " if day < 10 else "    ", h)
    # replace numbers at the end of a line
    pattern = rf" {day}\n"
    h = re.sub(pattern, "  \n" if day < 10 else "   \n", h)

print(h)

输出:

          May 2020
Mon Tue Wed Thu Fri Sat Sun
                  1   2   3
  4   5   6   7   8   9  10
 11  12  13  14  15  16  17
 18  19  20  21  22  23  24
 25  26  27  28  29  30  31


# after replacement    

          May 2020
Mon Tue Wed Thu Fri Sat Sun
                           
                           
                 15  16  17
 18  19  20  21  22  23  24
 25  26  27  28  29  30  31

推荐阅读