Returns a dict of date/time values to be used in a cron entry
194263
def _get_cron_date_time(**kwargs):
    '''
    
    '''
    # Define ranges (except daymonth, as it depends on the month)
    range_max = {
        'minute': list(list(range(60))),
        'hour': list(list(range(24))),
        'month': list(list(range(1, 13))),
        'dayweek': list(list(range(7)))
    }

    ret = {}
    for param in ('minute', 'hour', 'month', 'dayweek'):
        value = six.text_type(kwargs.get(param, '1')).lower()
        if value == 'random':
            ret[param] = six.text_type(random.sample(range_max[param], 1)[0])
        elif len(value.split(':')) == 2:
            cron_range = sorted(value.split(':'))
            start, end = int(cron_range[0]), int(cron_range[1])
            ret[param] = six.text_type(random.randint(start, end))
        else:
            ret[param] = value

    if ret['month'] in '1 3 5 7 8 10 12'.split():
        daymonth_max = 31
    elif ret['month'] in '4 6 9 11'.split():
        daymonth_max = 30
    else:
        # This catches both '2' and '*'
        daymonth_max = 28

    daymonth = six.text_type(kwargs.get('daymonth', '1')).lower()
    if daymonth == 'random':
        ret['daymonth'] = \
            six.text_type(random.sample(list(list(range(1, (daymonth_max + 1)))), 1)[0])
    else:
        ret['daymonth'] = daymonth

    return ret
14459
def event_log_filter_between_date(start, end, utc):
    
    return {
        'operation': 'betweenDate',
        'options': [
            {'name': 'startDate', 'value': [format_event_log_date(start, utc)]},
            {'name': 'endDate', 'value': [format_event_log_date(end, utc)]}
        ]
    }
614203
def get_utc_date(entry):
    """"""
    if entry['numeric_date_stamp'] == '0':
        entry['numeric_date_stamp_utc'] = '0'
        return entry

    else:
        if '.' in entry['numeric_date_stamp']:
            t = datetime.strptime(entry['numeric_date_stamp'],
                    '%Y%m%d%H%M%S.%f')
        else:
            t = datetime.strptime(entry['numeric_date_stamp'],
                    '%Y%m%d%H%M%S')
        tdelta = timedelta(hours = int(entry['tzone'][1:3]),
                minutes = int(entry['tzone'][3:5]))

        if entry['tzone'][0] == '-':
            ut = t + tdelta
        else:
            ut = t - tdelta

        entry['numeric_date_stamp_utc'] = ut.strftime('%Y%m%d%H%M%S.%f')

        return entry
456853
def _dates(self, key, value):
    
    if value.get('q'):
        self['date_proposed'] = normalize_date(value['q'])
    if value.get('r'):
        self['date_approved'] = normalize_date(value['r'])
    if value.get('s'):
        self['date_started'] = normalize_date(value['s'])
    if value.get('c'):
        self['date_cancelled'] = normalize_date(value['c'])
    if value.get('t'):
        self['date_completed'] = normalize_date(value['t'])

    raise IgnoreKey
1177090
def _timestamp_to_json_parameter(value):
    
    if isinstance(value, datetime.datetime):
        if value.tzinfo not in (None, UTC):
            # Convert to UTC and remove the time zone info.
            value = value.replace(tzinfo=None) - value.utcoffset()
        value = "%s %s+00:00" % (value.date().isoformat(), value.time().isoformat())
    return value
1036070
def cql_encode_datetime(self, val):
        
        timestamp = calendar.timegm(val.utctimetuple())
        return str(long(timestamp * 1e3 + getattr(val, 'microsecond', 0) / 1e3))
145994
def time_entries(self, start_date=None, end_date=None):
        ''''''
        if self.cache['time_entries']: return self.cache['time_entries']
        if not start_date:
            start_date = datetime.date(1900, 1, 1)
        if not end_date:
            end_date = datetime.date.today()
        time_entry_xml = self.bc.list_time_entries(self.id, start_date, end_date)
        time_entries = []
        for entry in ET.fromstring(time_entry_xml).findall("time-entry"):
            time_entries.append(TimeEntry(entry))
        self.cache['time_entries'] = time_entries
        return self.cache['time_entries']
1052076
def _GetDateValuesWithEpoch(self, number_of_days, date_time_epoch):
    
    return self._GetDateValues(
        number_of_days, date_time_epoch.year, date_time_epoch.month,
        date_time_epoch.day_of_month)
4635
def _parse_crontab(self, which, entry):
        '''
        
        '''

        # this handles day of week/month abbreviations
        def _fix(it):
            if which in _alternate and not it.isdigit():
                if it in _alternate[which]:
                    return _alternate[which][it]
            _assert(it.isdigit(),
                "invalid range specifier: %r (%r)", it, entry)
            it = int(it, 10)
            _assert(_start <= it <= _end_limit,
                "item value %r out of range [%r, %r]",
                it, _start, _end_limit)
            return it

        # this handles individual items/ranges
        def _parse_piece(it):
            if '-' in it:
                start, end = map(_fix, it.split('-'))
                # Allow "sat-sun"
                if which in (DAY_OFFSET, WEEK_OFFSET) and end == 0:
                    end = 7
            elif it == '*':
                start = _start
                end = _end
            else:
                start = _fix(it)
                end = _end
                if increment is None:
                    return set([start])

            _assert(_start <= start <= _end_limit,
                "%s range start value %r out of range [%r, %r]",
                _attribute[which], start, _start, _end_limit)
            _assert(_start <= end <= _end_limit,
                "%s range end value %r out of range [%r, %r]",
                _attribute[which], end, _start, _end_limit)
            _assert(start <= end,
                "%s range start value %r > end value %r",
                _attribute[which], start, end)

            if increment:
                next_value = start + increment
                _assert(next_value <= _end_limit,
                        "first next value %r is out of range [%r, %r]",
                        next_value, start, _end_limit)
            return set(range(start, end+1, increment or 1))

        _start, _end = _ranges[which]
        _end_limit = _end
        # wildcards
        if entry in ('*', '?'):
            if entry == '?':
                _assert(which in (DAY_OFFSET, WEEK_OFFSET),
                    "cannot use '?' in the %r field", _attribute[which])
            return None, _end

        # last day of the month
        if entry == 'l':
            _assert(which == DAY_OFFSET,
                "you can only specify a bare 'L' in the 'day' field")
            return None, _end

        # for the last 'friday' of the month, for example
        elif entry.startswith('l'):
            _assert(which == WEEK_OFFSET,
                "you can only specify a leading 'L' in the 'weekday' field")
            es, _, ee = entry[1:].partition('-')
            _assert((entry[1:].isdigit() and 0 <= int(es) <= 7) or
                    (_ and es.isdigit() and ee.isdigit() and 0 <= int(es) <= 7 and 0 <= int(ee) <= 7),
                "last <day> specifier must include a day number or range in the 'weekday' field, you entered %r", entry)
            return None, _end

        # allow Sunday to be specified as weekday 7
        if which == WEEK_OFFSET:
            _end_limit = 7

        increment = None
        # increments
        if '/' in entry:
            entry, increment = entry.split('/')
            increment = int(increment, 10)
            _assert(increment > 0,
                "you can only use positive increment values, you provided %r",
                increment)
            _assert(increment <= _end_limit,
                    "increment value must be less than %r, you provided %r",
                    _end_limit, increment)

        # handle singles and ranges
        good = _parse_piece(entry)

        # change Sunday to weekday 0
        if which == WEEK_OFFSET and 7 in good:
            good.discard(7)
            good.add(0)

        return good, _end
442492
def pythonvaluetotime(time_val):
    ""
    if time_val is None:
        return None
    elif isinstance(time_val, numeric):
        return str(long(time_val * 1000.0))
    elif isinstance(time_val, date):
        dtlist = [time_val.year, time_val.month, time_val.day]
        if isinstance(time_val, datetime.datetime):
            dtlist += [time_val.hour, time_val.minute, time_val.second]
        else:
            dtlist += [0, 0, 0]
        return long(calendar.timegm(dtlist) * 1000.0)
    elif (isinstance(time_val, sequence)
                    and len(time_val) == 2):
        if all(isinstance(x, numeric) 
               for x in time_val):
            return ",".join(pythonvaluetotime(x) 
                            for x in time_val)
        elif all(isinstance(x, date) 
               for x in time_val):
            return ",".join(pythonvaluetotime(x) 
                            for x in time_val)
    raise ValueError(repr(time_val))
481073
def _ExtractCronJobIdFromPath(entry, event):
  """"""
  match = re.match(r".*cron-job/([^/]+).*", entry.http_request_path)
  if match:
    event.urn = "aff4:/cron/{}".format(match.group(1))
780124
def time_slice(self,timerange,surf=False):
        '''
        
        '''
        if isinstance(timerange[0],str): trange = cnes_convert(timerange)[0]
        else: trange=timerange
        return self.slice('date',trange,surf=surf)
659491
def get_osid_temporal_mdata():
    """"""
    return {
        'start_date': {
            'element_label': {
                'text': 'Start Date',
                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
                'formatTypeId': str(DEFAULT_FORMAT_TYPE),
            },
            'instructions': {
                'text': 'enter a valid datetime object.',
                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
                'formatTypeId': str(DEFAULT_FORMAT_TYPE),
            },
            'required': True,
            'read_only': False,
            'linked': False,
            'array': False,
            'default_date_time_values': [datetime.datetime.min],
            'syntax': 'DATETIME',
            'date_time_set': [],
        },
        'end_date': {
            'element_label': {
                'text': 'Start Date',
                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
                'formatTypeId': str(DEFAULT_FORMAT_TYPE),
            },
            'instructions': {
                'text': 'enter a valid datetime object.',
                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
                'formatTypeId': str(DEFAULT_FORMAT_TYPE),
            },
            'required': True,
            'read_only': False,
            'linked': False,
            'array': False,
            'default_date_time_values': [datetime.datetime.max],
            'syntax': 'DATETIME',
            'date_time_set': [],
        }
    }
198748
def get_calendar_entries(context, year=None, month=None,
                         template='zinnia/tags/entries_calendar.html'):
    
    if not (year and month):
        day_week_month = (context.get('day') or
                          context.get('week') or
                          context.get('month'))
        publication_date = getattr(context.get('object'),
                                   'publication_date', None)
        if day_week_month:
            current_month = day_week_month
        elif publication_date:
            if settings.USE_TZ:
                publication_date = timezone.localtime(publication_date)
            current_month = publication_date.date()
        else:
            today = timezone.now()
            if settings.USE_TZ:
                today = timezone.localtime(today)
            current_month = today.date()
        current_month = current_month.replace(day=1)
    else:
        current_month = date(year, month, 1)

    dates = list(map(
        lambda x: settings.USE_TZ and timezone.localtime(x).date() or x.date(),
        Entry.published.datetimes('publication_date', 'month')))

    if current_month not in dates:
        dates.append(current_month)
        dates.sort()
    index = dates.index(current_month)

    previous_month = index > 0 and dates[index - 1] or None
    next_month = index != len(dates) - 1 and dates[index + 1] or None
    calendar = Calendar()

    return {'template': template,
            'next_month': next_month,
            'previous_month': previous_month,
            'calendar': calendar.formatmonth(
                current_month.year,
                current_month.month,
                previous_month=previous_month,
                next_month=next_month)}
868128
def parse_date(string, force_datetime=False):
    
    matches = DATE.match(string)
    if not matches:
        return None

    values = dict([
        (
            k,
            v if v[0] in '+-' else int(v)
        ) for k,v in matches.groupdict().items() if v and int(v)
    ])

    if 'timestamp' in values:
        value = datetime.datetime.utcfromtimestamp(0) + datetime.timedelta(
            hours=int(values.get('offset_h', 0)),
            minutes=int(values.get('offset_m', 0)),
            seconds=int(values['timestamp']) / 1000.0
        )
        return value

    # I've made an assumption here, that a DateTime value will not
    # ever be YYYY-MM-DDT00:00:00, which is probably bad. I'm not
    # really sure how to handle this, other than to hard-code the
    # names of the field that are actually Date rather than DateTime.
    if len(values) > 3 or force_datetime:
        return datetime.datetime(**values)

    # Sometimes Xero returns Date(0+0000), so we end up with no
    # values. Return None for this case
    if not values:
        return None

    return datetime.date(**values)
38324
def WriteCronJob(self, cronjob, cursor=None):
    """"""
    query = ("INSERT INTO cron_jobs "
             "(job_id, job, create_time, enabled) "
             "VALUES (%s, %s, FROM_UNIXTIME(%s), %s) "
             "ON DUPLICATE KEY UPDATE "
             "enabled=VALUES(enabled)")

    create_time_str = mysql_utils.RDFDatetimeToTimestamp(
        cronjob.created_at or rdfvalue.RDFDatetime.Now())
    cursor.execute(query, [
        cronjob.cron_job_id,
        cronjob.SerializeToString(), create_time_str, cronjob.enabled
    ])
528219
def load_dostime(buf, pos):
    """"""
    stamp, pos = load_le32(buf, pos)
    tup = parse_dos_time(stamp)
    return to_datetime(tup), pos