def __init__(self, year, month, day, d=None): if d is None: d = JS("""new Date(@{{year}}, @{{month}} - 1, @{{day}}, 0, 0, 0, 0)""") self._d = d self.year = d.getFullYear() self.month = d.getMonth() + 1.0 self.day = d.getDate()
def gmtime(t=None): if t is None: t = time() date = JS("new Date(@{{t}}*1000)") tm = struct_time() tm_year = tm.tm_year = int(date.getUTCFullYear()) tm.tm_mon = int(date.getUTCMonth()) + 1 tm.tm_mday = int(date.getUTCDate()) tm.tm_hour = int(date.getUTCHours()) tm.tm_min = int(date.getUTCMinutes()) tm.tm_sec = int(date.getUTCSeconds()) tm.tm_wday = (int(date.getUTCDay()) + 6) % 7 tm.tm_isdst = 0 startOfYear = JS("new Date('Jan 1 '+ @{{tm_year}} +' GMT+0000')") tm.tm_yday = 1 + int((t - startOfYear.getTime()/1000)/86400) return tm
def mktime(t): """mktime(tuple) -> floating point number Convert a time tuple in local time to seconds since the Epoch.""" tm_year = t.tm_year tm_mon = t.tm_mon - 1 tm_mday = t.tm_mday tm_hour = t.tm_hour tm_min = t.tm_min tm_sec = t.tm_sec date = JS("new Date(@{{tm_year}}, @{{tm_mon}}, @{{tm_mday}}, @{{tm_hour}}, @{{tm_min}}, @{{tm_sec}})") # local time utc = JS("Date.UTC(@{{tm_year}}, @{{tm_mon}}, @{{tm_mday}}, @{{tm_hour}}, @{{tm_min}}, @{{tm_sec}})")/1000 ts = date.getTime() / 1000 if t[8] == 0: if ts - utc == timezone: return ts return ts + _dst return ts
def _strptime(datestring, format): try: return float( JS("strptime(@{{datestring}}.valueOf(), @{{format}}.valueOf()).getTime() / 1000.0" )) except: raise ValueError( "Invalid or unsupported values for strptime: '%s', '%s'" % (datestring, format))
def strptime(datestring, format): try: tt = localtime( float( JS("strptime(@{{datestring}}.valueOf(), @{{format}}.valueOf()).getTime() / 1000.0" ))) tt.tm_isdst = -1 return tt except: raise ValueError( "Invalid or unsupported values for strptime: '%s', '%s'" % (datestring, format))
def mktime(t): """mktime(tuple) -> floating point number Convert a time tuple in local time to seconds since the Epoch.""" tm_year = t.tm_year tm_mon = t.tm_mon - 1 tm_mday = t.tm_mday tm_hour = t.tm_hour tm_min = t.tm_min tm_sec = t.tm_sec date = JS( "new Date(@{{tm_year}}, @{{tm_mon}}, @{{tm_mday}}, @{{tm_hour}}, @{{tm_min}}, @{{tm_sec}})" ) # local time utc = JS( "Date.UTC(@{{tm_year}}, @{{tm_mon}}, @{{tm_mday}}, @{{tm_hour}}, @{{tm_min}}, @{{tm_sec}})" ) / 1000 ts = date.getTime() / 1000 if t[8] == 0: if ts - utc == timezone: return ts return ts + _dst return ts
def __add__(self, other): if isinstance(other, timedelta): year = self.year month = self.month day = self.day + other.days hour = self.hour + (other.seconds / 3600.0) minute = self.minute + ((other.seconds / 60.0) % 60) second = self.second + (other.seconds % 60) microsecond = self.microsecond + other.microseconds d = JS("""new Date(@{{year}}, @{{month}}, @{{day}}, @{{hour}}, @{{minute}}, @{{second}}, @{{microsecond}})""") return datetime(0, 0, 0, 0, 0, 0, 0, None, d) else: raise TypeError("expected timedelta object")
def __init__(self, hour, minute=0, second=0, microsecond=0, tzinfo=None, d=None): if tzinfo != None: raise NotImplementedError("tzinfo") if d is None: d = JS("""new Date(1970, 1, 1, @{{hour}}, @{{minute}}, @{{second}}, 0.5 + @{{microsecond}} / 1000.0)""") self._d = d self.hour = d.getHours() self.minute = d.getMinutes() self.second = d.getSeconds() self.microsecond = d.getMilliseconds() * 1000.0 self.tzinfo = None
def __sub__(self, other): if isinstance(other, date) or isinstance(other, datetime): diff = self._d.getTime() - other._d.getTime() return timedelta(int(diff / 86400000.0), int(diff / 1000.0) % 86400, milliseconds=(diff % 86400000)) elif isinstance(other, timedelta): year = self.year month = self.month day = self.day - other.days hour = self.hour - (other.seconds / 3600.0) minute = self.minute - ((other.seconds / 60.0) % 60) second = self.second - (other.seconds % 60) microsecond = self.microsecond - other.microseconds d = JS("""new Date(@{{year}}, @{{month}}, @{{day}}, @{{hour}}, @{{minute}}, @{{second}}, @{{microsecond}})""") return datetime(0, 0, 0, 0, 0, 0, 0, None, d) else: raise TypeError("expected date or datetime object")
def isocalendar(self): isoyear = isoweeknr = isoweekday = None _d = self._d JS(""" var gregdaynumber = function(year, month, day) { var y = year; var m = month; if (month < 3) { y--; m += 12; } return Math.floor(365.25 * y) - Math.floor(y / 100) + Math.floor(y / 400) + Math.floor(30.6 * (m + 1)) + day - 62; }; var year = @{{_d}}.getFullYear(); var month = @{{_d}}.getMonth(); var day = @{{_d}}.getDate(); var wday = @{{_d}}.getDay(); @{{isoweekday}} = ((wday + 6) % 7) + 1; @{{isoyear}} = year; var d0 = gregdaynumber(year, 1, 0); var weekday0 = ((d0 + 4) % 7) + 1; var d = gregdaynumber(year, month + 1, day); @{{isoweeknr}} = Math.floor((d - d0 + weekday0 + 6) / 7) - Math.floor((weekday0 + 3) / 7); if ((month == 11) && ((day - @{{isoweekday}}) > 27)) { @{{isoweeknr}} = 1; @{{isoyear}} = @{{isoyear}} + 1; } if ((month == 0) && ((@{{isoweekday}} - day) > 3)) { d0 = gregdaynumber(year - 1, 1, 0); weekday0 = ((d0 + 4) % 7) + 1; @{{isoweeknr}} = Math.floor((d - d0 + weekday0 + 6) / 7) - Math.floor((weekday0 + 3) / 7); @{{isoyear}}--; } """) return (isoyear, isoweeknr, isoweekday)
def now(tz=None): if tz != None: raise NotImplementedError("tz") return datetime(0, 0, 0, 0, 0, 0, 0, None, JS("""new Date()"""))
def fromordinal(ordinal): d = JS("""new Date()""") d.setTime((ordinal - 719163.0) * 86400000.0) return datetime(0, 0, 0, 0, 0, 0, 0, None, d)
def sin(x): return float(JS("Math.sin(@{{x}}.valueOf())"))
def floor(x): return float(JS("Math.floor(@{{x}}.valueOf())"))
def ceil(x): return float(JS("Math.ceil(@{{x}}.valueOf())"))
def fromtimestamp(timestamp): d = JS("""new Date()""") d.setTime(timestamp * 1000.0) return date(0, 0, 0, d)
def fabs(x): return float(JS("Math.abs(@{{x}}.valueOf())"))
from prambanan import JS from time import __c__days, __c__months, strftime, localtime, gmtime, _strptime _strftime = strftime MINYEAR = 1 MAXYEAR = 1000000 # __Jan_01_0001 : local time for Mon Jan 01 0001 00:00:00 __Jan_01_0001 = JS("""(new Date((new Date('Jan 1 1971')).getTime() - 62167132800000)).getTime()""") class date(object): def __init__(self, year, month, day, d=None): if d is None: d = JS("""new Date(@{{year}}, @{{month}} - 1, @{{day}}, 0, 0, 0, 0)""") self._d = d self.year = d.getFullYear() self.month = d.getMonth() + 1.0 self.day = d.getDate() @staticmethod def today(): return date(0, 0, 0, JS("""new Date()""")) @staticmethod def fromtimestamp(timestamp): d = JS("""new Date()""") d.setTime(timestamp * 1000.0) return date(0, 0, 0, d) @staticmethod
def atan2(x, y): return float(JS("Math.atan2(@{{x}}.valueOf(), @{{y}}.valueOf())"))
def atan(x): return float(JS("Math.atan(@{{x}}.valueOf())"))
def acos(x): return float(JS("Math.acos(@{{x}}.valueOf())"))
def utcnow(): d = JS("""new Date()""") return datetime.utcfromtimestamp(int(d.getTime() / 1000.0))
def pow(x, y): return float(JS("Math.pow(@{{x}}.valueOf(), @{{y}}.valueOf())"))
def date(self): return JS("new __date(self.year, self.month, self.day)")
def log(x, base=None): if base is None: return float(JS("Math.log(@{{x}}.valueOf())")) return float( JS("Math.log(@{{x}}.valueOf()) / Math.log(@{{base}}.valueOf())"))
def exp(x): return float(JS("Math.exp(@{{x}}.valueOf())"))
def today(): return datetime(0, 0, 0, 0, 0, 0, 0, None, JS("""new Date()"""))
def fromordinal(ordinal): t = __Jan_01_0001 + (ordinal-1) * 86400000.0 d = JS("""new Date(@{{t}})""") return date(0, 0, 0, d)
def fromtimestamp(timestamp, tz=None): if tz != None: raise NotImplementedError("tz") d = JS("""new Date()""") d.setTime(timestamp * 1000.0) return datetime(0, 0, 0, 0, 0, 0, 0, None, d)
# Check http://docs.python.org/library/time.html from prambanan import JS import math timezone = JS("60 * (new Date(new Date().getFullYear(), 0, 1)).getTimezoneOffset()") altzone = JS("60 * (new Date(new Date().getFullYear(), 6, 1)).getTimezoneOffset()") if altzone > timezone: # Probably on southern parth of the earth... d = timezone timezone = altzone altzone = d _dst = timezone - altzone d = JS("(new Date(new Date().getFullYear(), 0, 1))") d = str(d.toLocaleString()).split()[-1] if d[0] == '(': d = d[1:-1] tzname = (d, None) del d __c__days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] __c__months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] def time(): return float(JS("new Date().getTime() / 1000.0")) class struct_time(object): n_fields = 9 n_sequence_fields = 9 n_unnamed_fields = 0 tm_year = None
def today(): return date(0, 0, 0, JS("""new Date()"""))
def strftime(fmt, t=None): if t is None: t = localtime() else: if not isinstance(t, struct_time) and len(t) != 9: raise TypeError('argument must be 9-item sequence, not float') tm_year = t.tm_year tm_mon = t.tm_mon tm_mday = t.tm_mday tm_hour = t.tm_hour tm_min = t.tm_min tm_sec = t.tm_sec tm_wday = t.tm_wday tm_yday = t.tm_yday date = JS("new Date(@{{tm_year}}, @{{tm_mon}} - 1, @{{tm_mday}}, @{{tm_hour}}, @{{tm_min}}, @{{tm_sec}})") startOfYear = JS("new Date(@{{tm_year}},0,1)") firstMonday = 1 - ((startOfYear.getDay() + 6) % 7) + 7 firstWeek = JS("new Date(@{{tm_year}},0,@{{firstMonday}})") weekNo = date.getTime() - firstWeek.getTime() if weekNo < 0: weekNo = 0 else: weekNo = 1 + int(weekNo/604800000) def format(c): if c == '%': return '%' elif c == 'a': return format('A')[:3] elif c == 'A': return __c__days[format('w')] elif c == 'b': return format('B')[:3] elif c == 'B': return __c__months[tm_mon-1] elif c == 'c': return date.toLocaleString() elif c == 'd': return "%02d" % tm_mday elif c == 'H': return "%02d" % tm_hour elif c == 'I': return "%02d" % (tm_hour % 12) elif c == 'j': return "%03d" % tm_yday elif c == 'm': return "%02d" % tm_mon elif c == 'M': return "%02d" % tm_min elif c == 'p': # FIXME: should be locale dependent if tm_hour < 12: return "AM" return "PM" elif c == 'S': return "%02d" % tm_sec elif c == 'U': raise NotImplementedError("strftime format character '%s'" % c) elif c == 'w': return "%d" % ((tm_wday+1) % 7) elif c == 'W': return "%d" % weekNo elif c == 'x': return "%s" % date.toLocaleDateString() elif c == 'X': return "%s" % date.toLocaleTimeString() elif c == 'y': return "%02d" % (tm_year % 100) elif c == 'Y': return "%04d" % tm_year elif c == 'Z': raise NotImplementedError("strftime format character '%s'" % c) return "%" + c result = '' remainder = fmt re_pct = JS("/([^%]*)%(.)(.*)/") JS("var a, fmtChar;") while remainder: JS("""{ @{{!a}} = @{{re_pct}}.exec(@{{remainder}}); if (!@{{!a}}) { @{{result}} += @{{remainder}}; @{{remainder}} = false; } else { @{{result}} += @{{!a}}[1]; @{{!fmtChar}} = @{{!a}}[2]; @{{remainder}} = @{{!a}}[3]; if (typeof @{{!fmtChar}} != 'undefined') { @{{result}} += @{{format}}(@{{!fmtChar}}); } } }""") return str(result)
def sqrt(x): return float(JS("Math.sqrt(@{{x}}.valueOf())"))
def localtime(t=None): if t is None: t = time() date = JS("new Date(@{{t}}*1000)") dateOffset = date.getTimezoneOffset() tm = struct_time() tm_year = tm.tm_year = int(date.getFullYear()) tm_mon = tm.tm_mon = int(date.getMonth()) + 1 tm_mday = tm.tm_mday = int(date.getDate()) tm.tm_hour = int(date.getHours()) tm.tm_min = int(date.getMinutes()) tm.tm_sec = int(date.getSeconds()) tm.tm_wday = (int(date.getDay()) + 6) % 7 tm.tm_isdst = 0 if timezone == 60*date.getTimezoneOffset() else 1 startOfYear = JS("new Date(@{{tm_year}},0,1)") # local time startOfYearOffset = startOfYear.getTimezoneOffset() startOfDay = JS("new Date(@{{tm_year}},@{{tm_mon}}-1,@{{tm_mday}})") dt = float(startOfDay.getTime() - startOfYear.getTime())/1000 dt = dt + 60 * (startOfYearOffset - dateOffset) tm.tm_yday = 1 + int(dt/86400.0) return tm
def __init__(self, year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, d=None): if d is None: d = JS("""new Date(@{{year}}, @{{month}} - 1, @{{day}}, @{{hour}}, @{{minute}}, @{{second}}, 0.5 + @{{microsecond}} / 1000.0)""") JS("__date.prototype.__init__.call(this, 0, 0, 0, @{{d}})") JS("__time.prototype.__init__.call(this, 0, 0, 0, 0, null, @{{d}})")