Find day of week from month and year

Donn Cave donn at u.washington.edu
Fri Sep 2 23:21:19 CEST 2005


In article <1125693378.950355.210830 at g49g2000cwa.googlegroups.com>,
 "Laguna" <ed_zeng at yahoo.com> wrote:

> > What do you mean by, "the 9 element tuple need to be populated
> > correctly"?  Do you need someone to tell you what values it
> > needs?  What happens if you use (2005, 9, 1, 0, 0, 0, 0, 0, 0),
> > for example?  If you make this tuple with localtime or gmtime,
> > do you know what the 7th (tm[6]) element of the tuple is?
> > What tricks did you try, exactly?
> >
> >    Donn Cave, donn at u.washington.edu
> 
> Thanks for pointing out. tm[6] = weekday, and tm[7] = Julian data, but
> I wouldn't know these values when my input values are month and year.
> 
> I will try out the more constructive suggestions from Paul and Robert.
> 
> Following is what I have tried. As you can tell, the results are wrong!
> 
> >>> import time
> >>> time.asctime((2003, 9, 1, 0, 0, 0, 0, 0, 0))
> 'Mon Sep 01 00:00:00 2003'
> >>> time.asctime((2003, 8, 1, 0, 0, 0, 0, 0, 0))
> 'Mon Aug 01 00:00:00 2003'
> >>> time.asctime((2003, 7, 1, 0, 0, 0, 0, 0, 0))
> 'Mon Jul 01 00:00:00 2003'

Well, sure, that tm value will certainly not be the
3rd Friday, but it does correctly represent the first
day of the month.  With localtime() you can find out
the day of the week, on the first day of the month.
When you know that, the 3rd Friday is simple arithmetic.

Since other followups have already spoon-fed you a
solution (assuming it works, haven't tried), here's an
example of what I mean -

    import time
    for m in range(1, 13):
        c1 = time.mktime((2005, m, 1, 0, 0, 0, 0, 0, 0))
        d1 = time.localtime(c1)[6]
        if d1 > 4:
                f3 = 26 - d1
        else:
                f3 = 19 - d1
        # f3 = 19 + (d1 // 5) * 7 - d1
        c3 = time.mktime((2005, m, f3, 0, 0, 0, 0, 0, 0))
        print time.ctime(c3)

I don't know if you intend to go on to do much more
programming after this, but that's who I normally
assume we're talking to here, programmers.  No one
knows everything and misses nothing, certainly not
me, but it's nice when people come to comp.lang.python
and can account for at least the beginning of some
analysis of their problem.  When that's missing, it's
hard to know what's really constructive.

   Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list