how many days each month

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • m2babaey
    New Member
    • Sep 2009
    • 2

    how many days each month

    Hi
    I was wondering how I can get the maximum actual value of the number of days that fall in a month
    For example, for April 2008, how many days it is. My python code requires this
    Thanks for your help
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    Here's a fairly trivial way (there are probably better ways, but I was just digging through the docshttp://docs.python.org/library/datet...etime.datetime

    Code:
    from datetime import *
    apr=date(2008,4,1)
    may=date(2008,5,1)
    days_in_apr=(may-apr).days
    Obviously if you were a little bit slick you'd implement a function which takes 4 or Apr and returns the number of days. There may be such a function, but I got distracted. Hopefully this gets you started...

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      I have played around with a dates class for the exercise. Following is a snippet of the code that may give you some ideas.
      Code:
      def isLeap(yr):
          if not yr % 4 and (yr % 100 or not yr % 400):
              return [None,31,29,31,30,31,30,31,31,30,31,30,31]
          return [None,31,28,31,30,31,30,31,31,30,31,30,31]
      
      monthDict = dict(zip(range(1,13),['January', 'February', 'March',
                                        'April', 'May', 'June', 'July',
                                        'August', 'September', 'October',
                                        'November', 'December']))
      
      # Date format MM/DD/YYYY
      datestr = "04/22/2001"
      month,day,year = [int(item) for item in datestr.split('/')]
      days_in_month = isLeap(year)[month]

      Comment

      Working...