source: TI07-MOLES/trunk/PythonCode/wsgi/Date.py @ 2533

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI07-MOLES/trunk/PythonCode/wsgi/Date.py@2533
Revision 2533, 2.1 KB checked in by lawrence, 13 years ago (diff)

Discovery now defaults to an advanced interface which is getting close
to that required by ticket:731. The first point on ticket:733 is now done too.

Line 
1def JulDay(d):
2    ''' This code based on madpo which was based on numerical recipes '''
3    #Gregorian calendar was adopted on October 15, 1582
4    day,month,year=map(int,d)
5    GregDay=15+31*(10+12*1582)
6    if year==0: raise 'JULDAY: no such thing as year zero'
7    if year<0: year=year+1
8    if month>2:
9        jy=year
10        jm=month+1
11    else:
12        jy=year-1
13        jm=month+13
14    julday=int(365.25*jy)+int(30.6001*jm)+day+1720995
15    if day+31*(month+12*year)>GregDay:
16        ja=int(0.01*jy)
17        julday=julday+2-ja+int(0.25*ja)
18    return julday
19       
20def LeapYear(year):
21    ''' Return a 1 if a leap year, 0 if not '''
22    year=int(year)
23    if year%4==0:
24        if year%100==0:
25            if year%400==0:
26                return 1
27            else:
28                return 0
29        else:
30            return 1
31    else:
32        return 0
33
34def ValidDate(d):
35    ''' Take a triple (d,m,y), and check validity '''
36    d=map(int,d)
37    m=[0,31,28,31,30,31,30,31,31,30,31,30,31]
38    #s=(1,32,60,91,121,152,182,213,244,274,305,335,366)
39    l=LeapYear(d[2])
40    if l: m[2]=29
41    if d[1]>13: return 0
42    if d[0]>m[d[1]]: return 0
43    return 1
44   
45def iMonth(s):
46    '''Take a month as 'mmm' and convert to an integer (or do
47    nothing if the month is blank '''
48    d={'':'','JAN':1,'FEB':2,'MAR':3,'APR':4,'MAY':5,'JUN':6,
49       'JUL':7,'AUG':8,'SEP':9,'OCT':10,'NOV':11,'DEC':12}
50    return d[s.upper()]
51
52import unittest
53
54class TestCase(unittest.TestCase):
55    def test_julday(self):
56        # Date checked from http://aa.usno.navy.mil/data/docs/JulianDate.html
57        self.assertEqual(JulDay((1,12,2001)),2452245)
58        self.assertEqual(JulDay((28,2,2004)),2453064)
59    def test_LeapYear(self):
60        self.assertEqual(LeapYear(1900),0)
61        self.assertEqual(LeapYear(2000),1)
62        self.assertEqual(LeapYear(2001),0)
63        self.assertEqual(LeapYear(2004),1)
64    def test_ValidDate(self):
65        self.assertEqual(ValidDate((1,1,2004)),1)
66        self.assertEqual(ValidDate((29,2,2003)),0)
67        self.assertEqual(ValidDate((29,2,2004)),1)
68        self.assertEqual(ValidDate((31,4,2003)),0)
69   
70
71   
72if __name__=="__main__":
73    unittest.main()   
Note: See TracBrowser for help on using the repository browser.