打印从今天开始的日历
Print a calendar starting from today's date
我想打印当月的日历,但从 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 天经验,它似乎足够愚蠢。
我希望最终结果看起来像这样:
基本上,我希望日历只显示该月的剩余天数,而不是整个月。
日历方法returns一个字符串。您可以使用常规的字符串操作方法在打印前修改字符串 - f.e。正则表达式替换:
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
我想打印当月的日历,但从 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 天经验,它似乎足够愚蠢。
我希望最终结果看起来像这样:
基本上,我希望日历只显示该月的剩余天数,而不是整个月。
日历方法returns一个字符串。您可以使用常规的字符串操作方法在打印前修改字符串 - f.e。正则表达式替换:
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