0

我正在尝试编写一个程序,它会给我一个很好的 .txt 文件来显示今年的日历,但是,我不想使用日历功能,而是使用datetime

我希望它具有以下格式(我希望它旁边有一周中每一天的前 3 个字母):

周二 1 月 1 日

1月2日星期三

一直到

12月31日星期二

(基本上 365 行,每行 10 个字符,每行以换行符“\n”结尾)。这是我从各种堆栈流问题、教程和模块中收集到的。至今没有成功。

import datetime
from datetime import date
textfile = file('new_file.txt','wt')
your_date.isoformat()
your_date.strftime("%A %d. %B %Y")

My main issue is that I am unfamiliar with how I get python to give me a range of dates (here being the year 2013, but it could also be just any increment in time such as June 2011 to December 2014) and of course to print the day of the week next to it. This way it could be adapted to any time period you might need this small calendar for. I was thinking maybe assigning every day's number (1 being Monday, 2 being Tuesday is the pattern if I'm correct) the first 3 letters of a day in the week so it's all neat and of the same length.

4

2 回答 2

2

Here's one way to do the looping:

inc = datetime.timedelta(days=1)
curr = datetime.date(2013, 1, 1)
end = datetime.date(2014, 1, 1)
while curr < end:
    # print out the date and whatnot
    curr += inc
于 2013-03-30T21:24:37.947 回答
0
#!/usr/bin/env python3
import sys
from datetime import date, timedelta

def gen_calendar(year=None):
    if year is None:
        year = date.today().year

    current = date(year, 1, 1)
    delta   = timedelta(days=1)

    while current.year == year:
        yield current.strftime('%a %b %d')
        current += delta

if __name__ == '__main__':
    year = None
    if len(sys.argv) > 1:
        year = int(sys.argv[1])

    for str_date in gen_calendar(year):
        print(str_date)

this will print to stdout so you can redirect it to a file from the console, which is the usual but if you want to write to the file directly from the script replace the last two lines with this:

    with open('calendar.txt', 'w') as f:
        for str_date in gen_calendar(year):
            print(str_date, file=f)
于 2013-03-30T21:59:39.737 回答