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

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

A date handling utility

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
45import unittest
46
47class TestCase(unittest.TestCase):
48    def test_julday(self):
49        # Date checked from http://aa.usno.navy.mil/data/docs/JulianDate.html
50        self.assertEqual(JulDay((1,12,2001)),2452245)
51        self.assertEqual(JulDay((28,2,2004)),2453064)
52    def test_LeapYear(self):
53        self.assertEqual(LeapYear(1900),0)
54        self.assertEqual(LeapYear(2000),1)
55        self.assertEqual(LeapYear(2001),0)
56        self.assertEqual(LeapYear(2004),1)
57    def test_ValidDate(self):
58        self.assertEqual(ValidDate((1,1,2004)),1)
59        self.assertEqual(ValidDate((29,2,2003)),0)
60        self.assertEqual(ValidDate((29,2,2004)),1)
61        self.assertEqual(ValidDate((31,4,2003)),0)
62   
63
64   
65if __name__=="__main__":
66    unittest.main()   
Note: See TracBrowser for help on using the repository browser.