Encode a msgpck'ed datetime.
10028
def _encode_datetime(obj):
    """"""

    if isinstance(obj, datetime.datetime):
        obj = {'__datetime__': True, 'as_str': obj.strftime("%Y%m%dT%H:%M:%S.%f").encode()}
    return obj
962113
def to_isostring(dt):
    
    if dt.tzinfo is not None and dt.tzinfo.utcoffset(dt) > timedelta(0):
        logging.warn('Warning: aware datetimes are interpreted as if they were naive')

    # -3 to change microseconds to milliseconds
    return dt.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
957930
def _encode(cls, value):
        """"""

        value = json.dumps(value)
        return cls._ENC_RE.sub(lambda x: '%%%2x' % ord(x.group(0)), value)
1234170
function encodeDate(date) {
	if (!(date instanceof Date)) throw new Error('Value not Date: ' + date)
	return (date.getUTCFullYear() * monthsPerYear + date.getUTCMonth()) - yearMonthZero
}
1242947
def datetime_handler(x):
    
    if isinstance(x, datetime.datetime) or isinstance(x, datetime.date):
        return x.isoformat()
    raise TypeError("Unknown type")
301358
def unixtime_to_datetimestr(unixtime, timefmt='%Y/%m/%d %H:%M:%S', isutc=True):
    
    try:
        if unixtime == -1:
            return 'NA'
        if unixtime is None:
            return None
        if isutc:
            return datetime.datetime.utcfromtimestamp(unixtime).strftime(timefmt)
        else:
            return datetime.datetime.fromtimestamp(unixtime).strftime(timefmt)
    except ValueError:
        raise
1373264
def encode(self, value):
        
        if type(value) is not datetime.datetime:
            raise TypeError('encode() argument must be a Python datetime')

        coarse = Time32Type().encode(value)
        fine   = Time8Type() .encode(value.microsecond / 1e6)

        return coarse + fine
1319638
def encode(timestamp):
    
    seconds = int(timestamp)
    nanoseconds = int((timestamp - seconds) * 1000000000)
    seconds = seconds + _OFFSET
    encoded = b2a_hex(struct.pack(_STRUCTURE, seconds, nanoseconds))
    return "@" + encoded.decode("ascii")
182596
def ms_to_datetime(ms, tzinfo=None):
    """"""
    if not isinstance(ms, (int, long)):
        raise TypeError('expected integer, not %s' % type(ms))

    if tzinfo is None:
        tzinfo = mktz()

    return datetime.datetime.fromtimestamp(ms * 1e-3, tzinfo)
504326
def _datetime_to_utc(self, dt):
        """"""

        if not dt.tzinfo:
            dt = dt.replace(tzinfo=tz.gettz())
        return dt.astimezone(tz.gettz('UTC'))
736866
def encode_date_optional_time(obj):
    
    if isinstance(obj, datetime.datetime):
        return timezone("UTC").normalize(obj.astimezone(timezone("UTC"))).strftime('%Y-%m-%dT%H:%M:%SZ')
    raise TypeError("{0} is not JSON serializable".format(repr(obj)))
814819
def date(fmt=None,timestamp=None):
    ""
    if fmt=='U': # return timestamp
        t = datetime.datetime.now()
        return int(time.mktime(t.timetuple()))
    if fmt=='c': # return isoformat 
        d = datetime.datetime.fromtimestamp(timestamp)
        return d.isoformat()
    if fmt=='Ymd':
        d = datetime.datetime.now()
        return d.strftime("%Y%m%d")
252075
def ms_to_timestamp(ms):
    """'"""
    # XXX throw on overflow/underflow?
    if ms < 0: ms = 0
    if ms > MAX_REPRESENTABLE_TIME: ms = MAX_REPRESENTABLE_TIME
    h, m, s, ms = ms_to_times(ms)
    return "%01d:%02d:%02d.%02d" % (h, m, s, ms//10)
158622
def str2unixtime(ts, fmt='%Y-%m-%d %H:%M:%S'):
    
    t = time.strptime(ts, fmt)
    return int(time.mktime(t))
152236
def _append_utc_datetime(self, tag, format, ts, precision, header):
        """"""

        if ts is None:
            t = datetime.datetime.utcnow()
        elif type(ts) is float:
            t = datetime.datetime.utcfromtimestamp(ts)
        else:
            t = ts

        s = t.strftime(format)
        if precision == 3:
            s += ".%03d" % (t.microsecond / 1000)
        elif precision == 6:
            s += ".%06d" % t.microsecond
        elif precision != 0:
            raise ValueError("Precision should be one of 0, 3 or 6 digits")

        return self.append_pair(tag, s, header=header)
917826
def stringToDate(fmt="%Y-%m-%d"):
    """"""
    import time
    import datetime
    def conv_func(s):
        return datetime.date(*time.strptime(s,fmt)[:3])
    return conv_func
364459
def date_decoder(dic):
    """"""
    if '__date__' in dic:
        try:
            d = datetime.date(**{c: v for c, v in dic.items() if not c == "__date__"})
        except (TypeError, ValueError):
            raise json.JSONDecodeError("Corrupted date format !", str(dic), 1)
    elif '__datetime__' in dic:
        try:
            d = datetime.datetime(**{c: v for c, v in dic.items() if not c == "__datetime__"})
        except (TypeError, ValueError):
            raise json.JSONDecodeError("Corrupted datetime format !", str(dic), 1)
    else:
        return dic
    return d