~mystic-mirage/mayanc/trunk

1 by Mystic-Mirage
init commit
1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3
11 by Mystic-Mirage
Add author and license information
4
# Author  :  Aleksandr Tishin /Mystic-Mirage/
5
# Email   :  <aleksandr.tishin@gmail.com>
6
7
# License :  Public Domain
8
10 by Mystic-Mirage
fix in bc calculations
9
from datetime import datetime
1 by Mystic-Mirage
init commit
10
from re import sub
11
2 by Mystic-Mirage
add default_sce variable, add command line options
12
import sys
13
from getopt import getopt
14
8 by Mystic-Mirage
major improvements and code rewrite
15
from _strptime import TimeRE
16
12 by Mystic-Mirage
add internationalization support
17
from os import path
18
import gettext
19
20
i18n_path = path.join(path.realpath(path.dirname(sys.argv[0])), 'locale')
21
if not path.isdir(i18n_path):
22
    i18n_path = None
23
gettext.install('mayanc', i18n_path)
24
1 by Mystic-Mirage
init commit
25
gmt = 584283
26
astronomical = 584285
27
28
default_cor = gmt
12 by Mystic-Mirage
add internationalization support
29
default_fmt = _('%C, %Z %H') # == %b.%k.%t.%w.%i, %z2 %z3 %h2 %h3
2 by Mystic-Mirage
add default_sce variable, add command line options
30
default_sce = 1
1 by Mystic-Mirage
init commit
31
8 by Mystic-Mirage
major improvements and code rewrite
32
def todaydatetuple():
33
    return datetime.today().timetuple()[:3]
34
35
def getmayandays(g_tuple = todaydatetuple(), cor = default_cor, \
7 by Mystic-Mirage
add support for bc dates, but 29 feb 1 bc can't be converted
36
        bc = False):
10 by Mystic-Mirage
fix in bc calculations
37
    i_year = 0
8 by Mystic-Mirage
major improvements and code rewrite
38
    if bc and g_tuple == (1, 2, 29):
39
        g_date = datetime(1, 3, 1)
10 by Mystic-Mirage
fix in bc calculations
40
        i_year = 1
8 by Mystic-Mirage
major improvements and code rewrite
41
    else:
42
        g_date = datetime(*g_tuple)
7 by Mystic-Mirage
add support for bc dates, but 29 feb 1 bc can't be converted
43
    if bc:
10 by Mystic-Mirage
fix in bc calculations
44
        if g_date < datetime(1, 3, 1) or g_date >= datetime(2, 1, 1):
45
            i_year = 1
7 by Mystic-Mirage
add support for bc dates, but 29 feb 1 bc can't be converted
46
        return ((g_date - datetime(g_date.year, 12, 31)).days \
47
                - datetime(g_date.year, 1, 1).toordinal() \
10 by Mystic-Mirage
fix in bc calculations
48
                + 1721426 - cor - i_year) % 1872000
7 by Mystic-Mirage
add support for bc dates, but 29 feb 1 bc can't be converted
49
    else:
50
        return (g_date.toordinal() + 1721425 - cor) % 1872000
1 by Mystic-Mirage
init commit
51
2 by Mystic-Mirage
add default_sce variable, add command line options
52
def getlongcount(m_days, scenario = default_sce):
1 by Mystic-Mirage
init commit
53
    d = m_days
54
    result = []
55
    for i in (144000, 7200, 360, 20, 1):
56
        t, d = divmod(d, i)
57
        result.append(t)
6 by Mystic-Mirage
minor improvements; two command line options added --gmt and --astronomical
58
    if scenario == 1 and not True in map(bool, result) or \
59
            scenario == 2 and not result[0]:
1 by Mystic-Mirage
init commit
60
        result[0] = 13
61
    return tuple(result)
62
63
def gettzolkin(m_days):
64
    return ((m_days + 19) % 20, (m_days + 3) % 13 + 1)
65
66
def gethaab(m_days):
67
    return divmod((m_days + 348) % 365, 20)
68
69
def getlord(m_days):
70
    return (m_days + 8) % 9 + 1
71
12 by Mystic-Mirage
add internationalization support
72
tzolkinlist = (_("Imix'"), _("Ik'"), _("Ak'b'al"), _("K'an"), \
73
        _("Chikchan"), _("Kimi"), _("Manik'"), _("Lamat"), _("Muluk"), \
74
        _("Ok"), _("Chuwen"), _("Eb'"), _("B'en"), _("Ix"), _("Men"), \
75
        _("K'ib'"), _("Kab'an"), _("Etz'nab'"), _("Kawak"), _("Ajaw"))
76
77
haablist = (_("Pop"), _("Wo"), _("Sip"), _("Sotz'"), _("Tzek"), \
78
        _("Xul"), _("Yaxk'"), _("Mol"), _("Ch'en"), _("Yax"), \
79
        _("Sac"), _("Keh"), _("Mak"), _("K'ank'in"), _("Muwan"), \
80
        _("Pax"), _("K'ayab'"), _("Kumk'u"), _("Wayeb'"))
81
82
lordlist = (_("G1"), _("G2"), _("G3"), _("G4"), _("G5"), _("G6"), \
83
        _("G7"), _("G8"), _("G9"))
1 by Mystic-Mirage
init commit
84
8 by Mystic-Mirage
major improvements and code rewrite
85
def getmayandatetuple(g_tuple = todaydatetuple(), cor = default_cor, \
7 by Mystic-Mirage
add support for bc dates, but 29 feb 1 bc can't be converted
86
        scenario = default_sce, bc = False):
8 by Mystic-Mirage
major improvements and code rewrite
87
    days = getmayandays(g_tuple, cor, bc)
6 by Mystic-Mirage
minor improvements; two command line options added --gmt and --astronomical
88
    return getlongcount(days, scenario) + gettzolkin(days) + \
89
            gethaab(days) + (getlord(days),)
3 by Mystic-Mirage
add getmayandatetuple function; getmayandate rewrited
90
8 by Mystic-Mirage
major improvements and code rewrite
91
def getmayandate(g_tuple = todaydatetuple(), cor = default_cor, \
7 by Mystic-Mirage
add support for bc dates, but 29 feb 1 bc can't be converted
92
        fmt = default_fmt, scenario = default_sce, bc = False):
8 by Mystic-Mirage
major improvements and code rewrite
93
    m_tuple = getmayandatetuple(g_tuple, cor, scenario, bc)
1 by Mystic-Mirage
init commit
94
    for s, r in map(lambda x, y: ('%' + x, str(y)), \
6 by Mystic-Mirage
minor improvements; two command line options added --gmt and --astronomical
95
            ('C', 'Z', 'H', 'b', 'k', 't', 'w', 'i', 'z1', 'z2', \
9 by Mystic-Mirage
fixing and improving output formatting
96
                'h1', 'h2', 'l', 'z3', 'h3', 'L'), \
97
            ('%b.%k.%t.%w.%i', '%z2 %z3', '%h2 %h3') + m_tuple + \
6 by Mystic-Mirage
minor improvements; two command line options added --gmt and --astronomical
98
                (tzolkinlist[m_tuple[5]], haablist[m_tuple[7]], \
99
                lordlist[m_tuple[9] - 1])):
1 by Mystic-Mirage
init commit
100
        fmt = sub(s, r, fmt)
101
    return fmt
102
8 by Mystic-Mirage
major improvements and code rewrite
103
def strpdate(data_string, format = '%Y-%m-%d', bc = False):
104
    _TimeRE_cache = TimeRE()
105
    _regex_cache = {}
106
    try:
107
        format_regex = _TimeRE_cache.compile(format)
108
    # KeyError raised when a bad format is found; can be specified as
109
    # \\, in which case it was a stray % but with a space after it
110
    except KeyError, err:
111
        bad_directive = err.args[0]
112
        if bad_directive == "\\":
113
            bad_directive = "%"
114
        del err
115
        raise ValueError("'%s' is a bad directive in format '%s'" %
116
                            (bad_directive, format))
117
    # IndexError only occurs when the format string is "%"
118
    except IndexError:
119
        raise ValueError("stray %% in format '%s'" % format)
120
    _regex_cache[format] = format_regex
121
    found = format_regex.match(data_string)
122
    if not found:
123
        raise ValueError("time data %r does not match format %r" %
124
                         (data_string, format))
125
    if len(data_string) != found.end():
126
        raise ValueError("unconverted data remains: %s" %
127
                          data_string[found.end():])
128
    date = list(todaydatetuple())
129
    found_dict = found.groupdict()
130
    for group_key in found_dict.iterkeys():
131
        if group_key == 'y':
132
            date[0] = int(found_dict['y'])
133
            if date[0] <= 68:
134
                date[0] += 2000
135
            else:
136
                date[0] += 1900
137
        elif group_key == 'Y':
138
            date[0] = int(found_dict['Y'])
139
        elif group_key == 'm':
140
            date[1] = int(found_dict['m'])
141
        elif group_key == 'd':
142
            date[2] = int(found_dict['d'])
143
    if not (bc and date == [1, 2, 29]):
144
        datetime(*date)
145
    return tuple(date)
146
6 by Mystic-Mirage
minor improvements; two command line options added --gmt and --astronomical
147
if __name__ == '__main__':
2 by Mystic-Mirage
add default_sce variable, add command line options
148
    correlation = default_cor
12 by Mystic-Mirage
add internationalization support
149
    gformat = _('%Y-%m-%d')
5 by Mystic-Mirage
extending date limits
150
    gdate = datetime.today().strftime(gformat)
2 by Mystic-Mirage
add default_sce variable, add command line options
151
    mformat = default_fmt
152
    scen = default_sce
7 by Mystic-Mirage
add support for bc dates, but 29 feb 1 bc can't be converted
153
    befc = False
6 by Mystic-Mirage
minor improvements; two command line options added --gmt and --astronomical
154
    optlist, args = getopt(sys.argv[1:], 'c:d:g:f:s:', \
155
            ['gmt', 'astronomical', 'baktun', 'katun', 'tun', 'winal', \
156
            'kin', 'tzol1', 'tzol2', 'tzol3', 'haab1', 'haab2', \
7 by Mystic-Mirage
add support for bc dates, but 29 feb 1 bc can't be converted
157
            'haab3', 'lord1', 'lord2', 'long', 'tzol', 'haab', 'bc'])
2 by Mystic-Mirage
add default_sce variable, add command line options
158
    for p, v in optlist:
159
        if p == '-c':
160
            if v == 'gmt':
161
                correlation = gmt
162
            elif v == 'astronomical':
163
                correlation = astronomical
164
            else:
165
                correlation = int(v)
6 by Mystic-Mirage
minor improvements; two command line options added --gmt and --astronomical
166
        elif p == '--gmt':
167
            correlation = gmt
168
        elif p == '--astronomical':
169
            correlation = astronomical
2 by Mystic-Mirage
add default_sce variable, add command line options
170
        elif p == '-d':
171
            gdate = v
172
        elif p == '-g':
173
            gformat = v
174
        elif p == '-f':
175
            mformat = v
176
        elif p == '-s':
177
            scen = int(v)
178
        elif p == '--baktun':
179
            mformat = '%b'
180
        elif p == '--katun':
181
            mformat = '%k'
182
        elif p == '--tun':
183
            mformat = '%t'
184
        elif p == '--winal':
185
            mformat = '%w'
186
        elif p == '--kin':
187
            mformat = '%i'
188
        elif p == '--tzol1':
189
            mformat = '%z1'
190
        elif p == '--tzol2':
191
            mformat = '%z2'
192
        elif p == '--tzol3':
9 by Mystic-Mirage
fixing and improving output formatting
193
            mformat = '%z3'
2 by Mystic-Mirage
add default_sce variable, add command line options
194
        elif p == '--haab1':
195
            mformat = '%h1'
196
        elif p == '--haab2':
197
            mformat = '%h2'
198
        elif p == '--haab3':
9 by Mystic-Mirage
fixing and improving output formatting
199
            mformat = '%h3'
2 by Mystic-Mirage
add default_sce variable, add command line options
200
        elif p == '--lord1':
201
            mformat = '%l'
202
        elif p == '--lord2':
203
            mformat = '%L'
4 by Mystic-Mirage
output formatting extension
204
        elif p == '--long':
205
            mformat = '%C'
206
        elif p == '--tzol':
207
            mformat = '%Z'
208
        elif p == '--haab':
209
            mformat = '%H'
7 by Mystic-Mirage
add support for bc dates, but 29 feb 1 bc can't be converted
210
        elif p == '--bc':
211
            befc = True
8 by Mystic-Mirage
major improvements and code rewrite
212
    print getmayandate(strpdate(gdate, gformat, befc), \
7 by Mystic-Mirage
add support for bc dates, but 29 feb 1 bc can't be converted
213
            correlation, mformat, scen, befc)