'Highlighting today's date in python using calendar.py in command prompt/windows powershell
I ran the following .py file using window's command prompt.
def main():
import calendar
from datetime import date
import time
# Converting 'datetime.date object to a string'
today=str(date.today())
# Generating a list of string like ['2021', '02', '02']
today=today.split("-")
#Converting string to integer
year=int(today[0])
month=int(today[1])
date=int(today[2])
print(calendar.month(year,month))
if __name__ == "__main__":
main()
It gave me the following output.
If I wanted to highlight today's date in windows command prompt like shown below, what would I have to do?
Solution 1:[1]
You can apply Console Virtual Terminal Sequences, e.g. as follows:
from datetime import date
import calendar
import time
import re
today = date.today()
year = today.year
month = today.month
thism = calendar.month(year,month) # current month
date = today.day.__str__().rjust(2)
rday = ('\\b' + date + '\\b').replace('\\b ', '\\s')
rdayc = "\033[7m" + date + "\033[0m"
# 7 Swaps foreground and background colors
print( re.sub(rday,rdayc,thism))
Works from cmd, powershell and pwsh regardless if run under conhost.exe or from Windows Terminal:
Solution 2:[2]
I used @JosefZ's answer and introduced a subclass of the TextCalendar:
import calendar
from datetime import datetime
today = datetime.today()
year = today.year
month = today.month
day = today.day
class DayInMonthHighlightingCalendar(calendar.TextCalendar):
def __init__(self, day_to_highlight=-1):
super().__init__()
self._day_to_highlight = day_to_highlight
def formatday(self, day: int, weekday: int, width: int) -> str:
s = super().formatday(day, weekday, width)
if day == self._day_to_highlight:
s = f"\033[7m{s}\033[0m"
return s
print(DayInMonthHighlightingCalendar(day_to_highlight=day).formatmonth(year, month))
The final effect is the same, but the code structure should be a bit clearer.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JosefZ |
| Solution 2 | maciek |



