allow extracting information from date

        http://www.sqlite.org/lang_datefunc.html
168106
def _normalize_date_SQL(self, field_name, field_kwargs, symbol):
        
        fstrs = []
        k_opts = {
            'day': "CAST(strftime('%d', {}) AS integer)",
            'hour': "CAST(strftime('%H', {}) AS integer)",
            'doy': "CAST(strftime('%j', {}) AS integer)", # day of year
            'julian_day': "strftime('%J', {})", # YYYY-MM-DD
            'month': "CAST(strftime('%m', {}) AS integer)",
            'minute': "CAST(strftime('%M', {}) AS integer)",
            'dow': "CAST(strftime('%w', {}) AS integer)", # day of week 0 = sunday
            'week': "CAST(strftime('%W', {}) AS integer)",
            'year': "CAST(strftime('%Y', {}) AS integer)"
        }

        for k, v in field_kwargs.items():
            fstrs.append([k_opts[k].format(self._normalize_name(field_name)), self.val_placeholder, v])

        return fstrs
1329254
def _wrap_extraction(self, date_object: datetime.datetime,
                        original_text: str,
                        start_char: int,
                        end_char: int
                        ) -> Extraction or None:
        
        try:
            resolution = self._settings[MIN_RESOLUTION] \
                    if self._settings[DATE_VALUE_RESOLUTION] == DateResolution.ORIGINAL \
                    else self._settings[DATE_VALUE_RESOLUTION]
            e = Extraction(self._convert_to_iso_format(date_object, resolution=resolution),
                           start_char=start_char,
                           end_char=end_char,
                           extractor_name=self._name,
                           date_object=date_object,
                           original_date=original_text)
            return e
        except Exception as e:
            warn('DateExtractor: Failed to wrap result ' + str(original_text) + ' with Extraction class.\n'
                                                                                'Catch ' + str(e))
            return None
1161934
function SQLDate($fmt, $col=false)
	{
		if (!$col) $col = $this->sysDate;
		$s = '';

		$len = strlen($fmt);
		for ($i=0; $i < $len; $i++) {
			if ($s) $s .= '||';
			$ch = $fmt[$i];
			switch($ch) {
			case 'Y':
			case 'y':
				$s .= "extract(year from $col)";
				break;
			case 'M':
			case 'm':
				$s .= "extract(month from $col)";
				break;
			case 'Q':
			case 'q':
				$s .= "cast(((extract(month from $col)+2) / 3) as integer)";
				break;
			case 'D':
			case 'd':
				$s .= "(extract(day from $col))";
				break;
			case 'H':
			case 'h':
				$s .= "(extract(hour from $col))";
				break;
			case 'I':
			case 'i':
				$s .= "(extract(minute from $col))";
				break;
			case 'S':
			case 's':
				$s .= "CAST((extract(second from $col)) AS INTEGER)";
				break;

			default:
				if ($ch == '\\') {
					$i++;
					$ch = substr($fmt,$i,1);
				}
				$s .= $this->qstr($ch);
				break;
			}
		}
		return $s;
	}
1353453
private List<O> findByDate(String dateField, Date start, Date end, int numObjects, boolean asc) {
        if (start == null)
            start = new Date(0);
        if (end == null)
            end = new Date();
        return getDatastore().find(clazz).filter(dateField + " >", start).filter(dateField + " <", end).order(asc ? dateField : '-' + dateField).limit(numObjects).asList();
    }
1277489
function parse_date_strings(root) {
    for (key in root) {
        if (!root.hasOwnProperty(key)) continue;
        var value = root[key];
        if (typeof(value) === 'object') { 
            parse_date_strings(value);
        } else if (typeof(value) === 'string' && /\d{4}-?\d{2}-?\d{2}(T?\d{2}:?\d{2}:?\d{2}(Z)?)?/.test(value)) {
            var timestamp = Date.parse(value);
            if (!isNaN(timestamp)) {
                root[key] = new Date(timestamp);
            }
        }
    }
}
646120
def formatDateParms(context, date_id):
    
    from_date = context.REQUEST.get('%s_fromdate' % date_id, None)
    to_date = context.REQUEST.get('%s_todate' % date_id, None)

    date_parms = {}
    if from_date and to_date:
        date_parms = 'from %s to %s' % (from_date, to_date)
    elif from_date:
        date_parms = 'from %s' % (from_date)
    elif to_date:
        date_parms = 'to %s' % (to_date)

    return date_parms
695302
def create_date_from_text(self, text):
        
        # Try to match dd/mm/yyyy format
        date_matches = re.match(self.DATE_LINE_REGEXP, text)

        # If no match, try with yyyy/mm/dd format
        if date_matches is None:
            date_matches = re.match(self.US_DATE_LINE_REGEXP, text)

        if date_matches is None:
            raise ValueError("No date could be extracted from the given value")

        # yyyy/mm/dd
        if len(date_matches.group(1)) == 4:
            return datetime.date(int(date_matches.group(1)), int(date_matches.group(2)), int(date_matches.group(3)))

        # dd/mm/yy
        if len(date_matches.group(3)) == 2:
            current_year = datetime.date.today().year
            current_millennium = current_year - (current_year % 1000)
            year = current_millennium + int(date_matches.group(3))
        # dd/mm/yyyy
        else:
            year = int(date_matches.group(3))

        return datetime.date(year, int(date_matches.group(2)), int(date_matches.group(1)))
994574
def parse(self, date, **kwargs):
        '''
        
        '''
        qualifiers = []
        if dateutil_parser is None:
            return None
        date = orig_date = date.strip()

        # various normalizations
        # TODO: call .lower() first
        date = date.replace('B.C.E.', 'BC')
        date = date.replace('BCE', 'BC')
        date = date.replace('B.C.', 'BC')
        date = date.replace('A.D.', 'AD')
        date = date.replace('C.E.', 'AD')
        date = date.replace('CE', 'AD')

        # deal with pre 0AD dates
        if date.startswith('-') or 'BC' in date or 'B.C.' in date:
            pre0AD = True
        else:
            pre0AD = False
        # BC seems to mess up parser
        date = date.replace('BC', '')

        # deal with circa: 'c.1950' or 'c1950'
        circa_match = re.match('([^a-zA-Z]*)c\.?\s*(\d+.*)', date)
        if circa_match:
            # remove circa bit
            qualifiers.append("Note 'circa'")
            date = ''.join(circa_match.groups())

        # deal with p1980 (what does this mean? it can appear in
        # field 008 of MARC records
        p_match = re.match("^p(\d+)", date)
        if p_match:
            date = date[1:]

        # Deal with uncertainty: '1985?'
        uncertainty_match = re.match('([0-9xX]{4})\?', date)
        if uncertainty_match:
            # remove the ?
            date = date[:-1]
            qualifiers.append('Uncertainty')

        # Parse the numbers intelligently
        # do not use std parser function as creates lots of default data
        res = dateutil_parser._parse(date, **kwargs)
        try:
            res = res[0]
        except:
            res = res
        if res is None:
            # Couldn't parse it
            return None
        # Note: Years of less than 3 digits not interpreted by
        #      dateutil correctly
        #      e.g. 87 -> 1987
        #           4  -> day 4 (no year)
        # Both cases are handled in this routine
        if res.year is None and res.day:
            year = res.day
        # If the whole date is simply two digits then dateutil_parser makes
        # it '86' -> '1986'. So strip off the '19'. (If the date specified
        # day/month then a two digit year is more likely to be this century
        # and so allow the '19' prefix to it.)
        elif self._numeric.match(date) and (len(date) == 2 or date.startswith('00')):
            year = res.year % 100
        else:
            year = res.year

        # finally add back in BC stuff
        if pre0AD:
            year = -year

        if not qualifiers:
            qualifier = ''
        else:
            qualifier = ', '.join(qualifiers) + (' : %s' % orig_date)
        return FlexiDate(year, res.month, res.day, res.hour, res.minute, res.second, res.microsecond, qualifier=qualifier)
571015
function toDate(str) {
  var millis = Date.parse(str);
  if (isNaN(millis)) {
    throw new Error(l10n.lookupFormat('typesDateNan', [ str ]));
  }
  return new Date(millis);
}
221783
def _extract_date(self):
        

        if self.date:
            return

        found = False

        for pattern in self.config.date:

            items = self.parsed_tree.xpath(pattern)

            if isinstance(items, basestring):
                # In case xpath returns only one element.
                items = [items]

            for item in items:
                if isinstance(item, basestring):
                    # '_ElementStringResult' object has no attribute 'text'
                    stripped_date = unicode(item).strip()

                else:
                    try:
                        stripped_date = item.text.strip()

                    except AttributeError:
                        # .text is None. We got a <div> item with span-only
                        # content. The result will probably be completely
                        # useless to a python developer, but at least we
                        # didn't fail handling the siteconfig directive.
                        stripped_date = etree.tostring(item)

                if stripped_date:
                    # self.date = strtotime(trim(elems, "; \t\n\r\0\x0B"))
                    self.date = stripped_date
                    LOGGER.info(u'Date extracted: %s.', stripped_date,
                                extra={'siteconfig': self.config.host})
                    found = True
                    break

            if found:
                break
54677
def extract_db_info(self, obj, keys):
        """"""

        objl = self.convert_in(obj)

        # FIXME: this is too complex
        if isinstance(objl, self.__class__):
            return objl.update_meta_info()

        try:
            with builtins.open(objl, mode='r') as fd:
                state = json.load(fd)
        except IOError as e:
            raise e

        result = super(BaseStructuredCalibration, self).extract_db_info(state, keys)

        try:
            minfo = state['meta_info']
            result['mode'] = minfo['mode_name']
            origin = minfo['origin']
            date_obs = origin['date_obs']
        except KeyError:
            origin = {}
            date_obs = "1970-01-01T00:00:00.00"

        result['instrument'] = state['instrument']
        result['uuid'] = state['uuid']
        result['tags'] = state['tags']
        result['type'] = state['type']
        result['observation_date'] = conv.convert_date(date_obs)
        result['origin'] = origin

        return result
119056
def _dump_date(d, delim):
    """"""
    if d is None:
        d = gmtime()
    elif isinstance(d, datetime):
        d = d.utctimetuple()
    elif isinstance(d, (integer_types, float)):
        d = gmtime(d)
    return "%s, %02d%s%s%s%s %02d:%02d:%02d GMT" % (
        ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")[d.tm_wday],
        d.tm_mday,
        delim,
        (
            "Jan",
            "Feb",
            "Mar",
            "Apr",
            "May",
            "Jun",
            "Jul",
            "Aug",
            "Sep",
            "Oct",
            "Nov",
            "Dec",
        )[d.tm_mon - 1],
        delim,
        str(d.tm_year),
        d.tm_hour,
        d.tm_min,
        d.tm_sec,
    )
605874
function getParsedDate(d, p) {
        var res, day;
        if ('string' === typeof d) {
            d = d === 'today' ? new Date() : new Date(d);
            // If invalid  date it return NaN.
            day = d.getDate();
            if (!day) return false;
        }
        try {
            res = {
                day: day || d.getDate(),
                month: d.getMonth() + 1,
                year: d.getFullYear(),
                obj: d
            };
        }
        catch(e) {
            return false;
        }
        res.str = (p.dayPos ? res.day + p.sep + res.month :
                   res.month + p.sep + res.day) + p.sep;
        res.str += p.yearDigits === 2 ? res.year.substring(3,4) : res.year;
        return res;
    }
533989
def daily404detail(date, limit=None, return_format=None):
    
    uri = 'daily404detail'
    if date:
        try:
            uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
        except AttributeError:
            uri = '/'.join([uri, date])
        if limit:
            uri = '/'.join([uri, str(limit)])
    return _get(uri, return_format)
765588
synchronized private static Date extractFromTimestamp(String watermark) {
    final SimpleDateFormat inputFormat = new SimpleDateFormat(INPUTFORMAT);
    final SimpleDateFormat outputFormat = new SimpleDateFormat(OUTPUTFORMAT);
    Date outDate = null;
    try {
      Date date = inputFormat.parse(watermark);
      String dateStr = outputFormat.format(date);
      outDate = outputFormat.parse(dateStr);
    } catch (ParseException e) {
      LOG.error(e.getMessage(), e);
    }
    return outDate;
  }
515191
def parse_date(dateString):
    ''''''
    if not dateString:
        return None
    for handler in _date_handlers:
        try:
            date9tuple = handler(dateString)
        except (KeyError, OverflowError, ValueError):
            continue
        if not date9tuple:
            continue
        if len(date9tuple) != 9:
            continue
        return date9tuple
    return None
605391
function getDayData(input){
    var data = csvTable(input,"\t");
    var today = new Date().getTime(); //getDateDDMMYYYY();
    var header = data[0];
    var column = 2;
    var minDiff = Number.MAX_SAFE_INTEGER;
    while(column<header.length){
        var columnDate =  new Date(header[column]+' 12:00:00 GMT-0500').getTime();
        if(Math.abs(today-columnDate)<minDiff){
            column++;
            minDiff = Math.abs(today-columnDate);
        }
        else{
            column--;
            break;
        }

    }
    if(column>=header.length){
        return null;
    }
    var result = new Array(data.length-1);
    for(var i=1;i<data.length;i++){
        result[i-1]={id:data[i][0],value:Number(data[i][column]),date:header[column]};

    }

    var table = new Array();
    table.push(result);
    for(var k=2;k<=column-1;k++){
        var row = new Array(data.length-1);
        for(var i=1;i<data.length;i++){
            row[i-1]={id:data[i][0],value:Number(data[i][k]),date:header[k]};
        }
        table.push(row);
    }

    return table;
}