Welcome, guest | Sign In | My Account | Store | Cart

simply prints the previous, current, or next day. Inputs may be year month month-day or year julian-day with the output in the same format.

Python, 63 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/env python
"""
        prints, based on input:
                current day
                previous day
                next day

        barbour
        29-Sep-2011
"""
import sys
import datetime

lsarg=len(sys.argv)
funcs={"previous":-1, "current":0, "next":1}

def yj2dt(y,jd):
        return datetime.datetime.strptime("%04i %03i"%(y,jd),"%Y %j")

def ymd2dt(y,m,md):
        return datetime.datetime.strptime("%04i %02i %02i"%(y,m,md),"%Y %m %d")

def dt2yj(dt):
        return dt.strftime("%Y %j")

def dt2ymd(dt):
        return dt.strftime("%Y %m %d")

def dayIter(base, daydelta):
        return base + datetime.timedelta(days = daydelta)

if __name__ == "__main__" and len(sys.argv)==1:
        print """
        usage:  func    year    day
        or      func    year    month   day

        'func' may be
                %s

        output will be the same as input (e.g. year julian, or year month day)
        """ % funcs.keys()

elif __name__ == "__main__" and lsarg > 1:

        fcn = str(sys.argv[1])

        try:
                deld = funcs[fcn]
        except KeyError:
                print "allowable functions:\n%s\n"%funcs.keys()
                raise

        if lsarg == 4:
                # year julian
                yy = int(sys.argv[2])
                jj = int(sys.argv[3])
                print dt2yj( dayIter( yj2dt(yy, jj), deld) )
        elif lsarg == 5:
                # year month day
                yy = int(sys.argv[2])
                mm = int(sys.argv[3])
                dd = int(sys.argv[4])
                print dt2ymd( dayIter( ymd2dt(yy, mm, dd), deld) )

Since datetime deals with leap year time issues, this is an easy way to traverse the year boundary if, for example, you're filtering data that crosses such a boundary. This is be used primarily as a shell script. If the file is named day.py and made executable, the following are examples:

% day.py previous 2009 1 1
2008 12 31

% day.py previous 2009 1
2008 366

2 comments

Enchanter Thunderbird 12 years, 6 months ago  # | flag

Why you got 366 for 2008? Special Year?

% day.py previous 2009 1 2008 366

Andy Barbour (author) 12 years, 6 months ago  # | flag

As expected, every year that has modulo(year,4)==0 (e.g. 2004, 2008, 2012, ...) is a leap year, meaning that the total number of days is 366, instead of 365.