python-3.x - 打印从今天开始的日历
问题描述
我想打印当月的日历,但从 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 天经验,它似乎很愚蠢,可以工作。
我希望最终结果看起来像这样:
本质上,我希望日历仅显示该月的剩余天数,而不是整个月。
解决方案
日历方法返回一个字符串。您可以使用传统的字符串操作方法在打印之前修改字符串 - 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
推荐阅读
- function - 我可以在 studio 5000 的结构化文本中声明用户定义的函数吗?
- laravel - Laravel - Maatwebsite Excel 导入仅存储在存储中,但不存储在数据库中
- javascript - 如何将增量添加到类的两个特定属性?
- android - Android 模拟器不工作:无法打开 /qemu.conf,找不到加速器等等
- python - 如何禁用 chromedriver selenium 上的视频?
- python - 如何从另一个函数启动 websocket 文件
- swift - 没有支撑框架的 SwiftUI 中心内容对齐
- r - 创建一个 For 循环以在 R 中重复 mutate 和 case_when 和 is.na 语句
- javascript - 引导程序中的日期选择器
- ionic-framework - 有没有办法同时激活两个离子侧菜单?