Question

I'm trying to write a program that will give me a nice .txt file displaying this year's calendar, however, I don't want to use the calendar function, but datetime.

I want it to have the following format (I want to have the first 3 letter of every day of the week next to it):

Tue Jan 01

Wed Jan 02

all the way to

Tue Dec 31

(basically 365 lines altogether with 10 characters in every line, and every line ends in a newline "\n"). This is what I have gathered going from various stackflow questions, tutorials and modules. So far no success.

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.

Was it helpful?

Solution 2

#!/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)

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top