Translate deadline date from human-acceptable format to the machine-acceptable
194724
def _parse_deadline(deadline):
        """"""
        if '-' in deadline and len(deadline) == 10:
            return deadline

        if '.' in deadline and len(deadline) == 10:  # russian format dd.mm.yyyy to yyyy-mm-dd
            dmy = deadline.split('.')
            if len(dmy) == 3 and all(v is not None for v in dmy):
                return '-'.join(reversed(dmy))

        raise exceptions.RumetrUnparsableDeadline()
1067604
def _to_desired_dates(self, arr):
        """"""
        times = utils.times.extract_months(
            arr[internal_names.TIME_STR], self.months
        )
        return arr.sel(time=times)
886443
def to_iso8601(value, strict=True, force_int=True):
    
    # split seconds to larger units
    # seconds = value.total_seconds()
    seconds = to_seconds(value, strict, force_int)

    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)
    days, hours = divmod(hours, 24)
    days, hours, minutes = map(int, (days, hours, minutes))
    seconds = round(seconds, 6)

    # build date
    date = ''
    if days:
        date = '%sD' % days

    # build time
    time = 'T'

    # hours
    bigger_exists = date or hours
    if bigger_exists:
        time += '{:02}H'.format(hours)

    # minutes
    bigger_exists = bigger_exists or minutes
    if bigger_exists:
        time += '{:02}M'.format(minutes)

    # seconds
    if isinstance(seconds, int) or force_int:
        seconds = '{:02}'.format(int(seconds))
    else:
        # 9 chars long w/leading 0, 6 digits after decimal
        seconds = '%09.6f' % seconds

    time += '{}S'.format(seconds)
    return 'P' + date + time
353605
function scheduleToSentence(schedule) {
    var outputText = locale.Every + ' ';

    if (schedule['h'] && schedule['m'] && schedule['h'].length <= 2 && schedule['m'].length <= 2) {
      // If there are only one or two specified values for
      // hour or minute, print them in HH:MM format

      var hm = [];
      for (var i = 0; i < schedule['h'].length; i++) {
        for (var j = 0; j < schedule['m'].length; j++) {
          hm.push(zeroPad(schedule['h'][i]) + ':' + zeroPad(schedule['m'][j]));
        }
      }
      if (hm.length < 2) {
        outputText = hm[0];
      } else {
        var lastVal = hm.pop();
        outputText = hm.join(', ') + ` ${locale.and} ` + lastVal;
      }
      if (!schedule['d'] && !schedule['D']) {
        outputText += ` ${locale['every day']}`;
      }
    } else {
      // Otherwise, list out every specified hour/minute value.

      if (schedule['h']) { // runs only at specific hours
        if (schedule['m']) { // and only at specific minutes
          outputText += numberList(schedule['m']) + ` ${locale['minute past the']} ` + numberList(schedule['h']) + ` ${locale['hour']}`;
        } else { // specific hours, but every minute
          outputText += `${locale['minute of']} ` + numberList(schedule['h']) + ` ${locale['hour']}`;
        }
      } else if (schedule['m']) { // every hour, but specific minutes
        outputText += numberList(schedule['m']) + ` ${locale['minute every hour']}`;
      } else { // cronspec has "*" for both hour and minute
        outputText += locale['minute'];
      }
    }

    if (schedule['D']) { // runs only on specific day(s) of month
      outputText += (locale['on the'] ? ` ${locale['on the']} ` : ' ') + numberList(schedule['D']);
      if (!schedule['M']) {
        outputText += ` ${locale['of every month']}`;
      }
    }

    if (schedule['d']) { // runs only on specific day(s) of week
      if (schedule['D']) {
        // if both day fields are specified, cron uses both; superuser.com/a/348372
        outputText += ` ${locale['and every']} `;
      } else {
        outputText += ` ${locale['on']} `;
      }
      outputText += dateList(schedule['d'], 'dow');
    }

    if (schedule['M']) {
      // runs only in specific months; put this output last
      outputText += ` ${locale['in']} ` + dateList(schedule['M'], 'mon');
    }

    return outputText;
  }
345673
def todate(val):
    '''
    '''
    if not val:
        raise ValueError("Value not provided")
    if isinstance(val, datetime):
        return val.date()
    elif isinstance(val, date):
        return val
    else:
        try:
            ival = int(val)
            sval = str(ival)
            if len(sval) == 8:
                return yyyymmdd2date(val)
            elif len(sval) == 5:
                return juldate2date(val)
            else:
                raise ValueError
        except Exception:
            # Try to convert using the parsing algorithm
            try:
                return date_from_string(val).date()
            except Exception:
                raise ValueError("Could not convert %s to date" % val)
642734
def parseEvent(self, result, i):
        """"""
        fmt = '%Y-%m-%dT%H:%M:%SZ'
        due = 0
        delay = 0
        real_time = 'n'
        number = result['stopEvents'][i]['transportation']['number']
        planned = datetime.strptime(result['stopEvents'][i]
            ['departureTimePlanned'], fmt)
        destination = result['stopEvents'][i]['transportation']['destination']['name']
        mode = self.get_mode(result['stopEvents'][i]['transportation']['product']['class'])
        estimated = planned
        if 'isRealtimeControlled' in result['stopEvents'][i]:
            real_time = 'y'
            estimated = datetime.strptime(result['stopEvents'][i]
                ['departureTimeEstimated'], fmt)
        # Only deal with future leave times
        if estimated > datetime.utcnow():
            due = self.get_due(estimated)
            delay = self.get_delay(planned, estimated)
            return[
                number,
                due,
                delay,
                planned,
                estimated,
                real_time,
                destination,
                mode
                ]
        else:
            return None
899987
def convert_date(value, parameter):
    '''
    
    '''
    value = _check_default(value, parameter, ( '', '-', None ))
    if value is None or isinstance(value, datetime.date):
        return value
    for fmt in settings.DATE_INPUT_FORMATS:
        try:
            return datetime.datetime.strptime(value, fmt).date()
        except (ValueError, TypeError):
            continue
    raise ValueError("`{}` does not match a format in settings.DATE_INPUT_FORMATS".format(value))
422864
def dateDict(date, prefix = ""):
    """"""
    res = {}

    res[prefix+"a"] = date.strftime("%a")
    res[prefix+"A"] = date.strftime("%A")
    res[prefix+"b"] = date.strftime("%b")
    res[prefix+"B"] = date.strftime("%B")
    res[prefix+"c"] = date.strftime("%c")
    res[prefix+"d"] = date.strftime("%d")
    res[prefix+"H"] = date.strftime("%H")
    res[prefix+"I"] = date.strftime("%I")
    res[prefix+"j"] = date.strftime("%j")
    res[prefix+"m"] = date.strftime("%m")
    res[prefix+"M"] = date.strftime("%M")
    res[prefix+"p"] = date.strftime("%p")
    res[prefix+"S"] = date.strftime("%S")
    res[prefix+"U"] = date.strftime("%U")
    res[prefix+"w"] = date.strftime("%w")
    res[prefix+"W"] = date.strftime("%W")
    res[prefix+"x"] = date.strftime("%x")
    res[prefix+"X"] = date.strftime("%X")
    res[prefix+"y"] = date.strftime("%y")
    res[prefix+"Y"] = date.strftime("%Y")
    res[prefix+"Z"] = date.strftime("%Z")

    for i, value in res.items():
        res[i] = locale_to_utf8(value)

    return res
1275770
private static String boundTimestamp(String input) {
		StringBuilder boundTimestamp = new StringBuilder();
		
		if (input == null) {
			input = "";
		}
		// MAKE SURE THE YEAR IS WITHIN LEGAL BOUNDARIES:
		boundTimestamp.append(boundDigits(input.substring(0,4),
				YEAR_LOWER_LIMIT, 
                                String.valueOf(Calendar.getInstance(TimeZone.getTimeZone("GMT")).get(Calendar.YEAR) )));

		// MAKE SURE THE MONTH IS WITHIN LEGAL BOUNDARIES:
		boundTimestamp.append(boundDigits(input.substring(4,6),
				MONTH_LOWER_LIMIT,MONTH_UPPER_LIMIT));
		
		// NOW DEPENDING ON THE YEAR + MONTH, MAKE SURE THE DAY OF MONTH IS
		// WITHIN LEGAL BOUNDARIES:
		int iYear = Integer.parseInt(boundTimestamp.substring(0,4));
		int iMonth = Integer.parseInt(boundTimestamp.substring(4,6));
		String maxDayOfMonth = getDaysInMonthBound(iYear, iMonth-1);

		boundTimestamp.append(boundDigits(input.substring(6,8),
				DAY_LOWER_LIMIT,maxDayOfMonth));
		
		// MAKE SURE THE HOUR IS WITHIN LEGAL BOUNDARIES:
		boundTimestamp.append(boundDigits(input.substring(8,10),
				HOUR_LOWER_LIMIT,HOUR_UPPER_LIMIT));
		
		// MAKE SURE THE MINUTE IS WITHIN LEGAL BOUNDARIES:
		boundTimestamp.append(boundDigits(input.substring(10,12),
				MINUTE_LOWER_LIMIT,MINUTE_UPPER_LIMIT));
		
		// MAKE SURE THE SECOND IS WITHIN LEGAL BOUNDARIES:
		boundTimestamp.append(boundDigits(input.substring(12,14),
				SECOND_LOWER_LIMIT,SECOND_UPPER_LIMIT));

		return boundTimestamp.toString();		
	}
768209
def _converter(self, value):
        """"""
        if not isinstance(value, datetime.date):
            raise TypeError('{0} is not valid date'.format(value))
        return value
596988
def handle_date(self, value):
        
        try:
            return iso8601.parse_date(unicode(value)).year
        except iso8601.ParseError:
            for datefmt in ("%B %d, %Y", "%Y-%m", "%Y-%m-%d", "%m/%d/%Y"):
                try:
                    # TODO: remove str coercion.
                    return datetime.strptime(unicode(value), datefmt).date().year
                except ValueError:
                    pass
299362
function datePrettyFormat(ms, opts) {
  if (typeof ms !== 'number') {
    throw new TypeError('Expected a number');
  }

  if (ms < 1000) {
    return Math.ceil(ms) + 'ms';
  }

  opts = opts || {};

  var secDecimalDigits = typeof opts.secDecimalDigits === 'number' ? opts.secDecimalDigits : 1;
  var ret = [];
  var parsed = formatDate(ms);

  ret = add(ret, parsed.years, 'y');
  ret = add(ret, parsed.days, 'd');
  ret = add(ret, parsed.hours, 'h');
  ret = add(ret, parsed.minutes, 'm');

  if (opts.compact) {
    ret = add(ret, parsed.seconds, 's');
    return '~' + ret[0];
  }

  ret = add(ret, (ms / 1000 % 60).toFixed(secDecimalDigits).replace(/\.0$/, ''), 's');

  return ret.join(' ');
}
1121479
def format(self):
        """"""
        act = self.actor
        time = self.time
        return u"{} {} {} <{}> {!s} {}\t{}\n".format(self.oldhexsha,
                                                     self.newhexsha,
                                                     act.name,
                                                     act.email,
                                                     time[0],
                                                     altz_to_utctz_str(time[1]),
                                                     self.message)
290543
def strtime(at=None, fmt=PERFECT_TIME_FORMAT):
    """"""
    if not at:
        at = utcnow()
    return at.strftime(fmt)
1168123
def _build_date_header_string(self, date_value):
		""""""
		if isinstance(date_value, datetime):
			date_value = time.mktime(date_value.timetuple())
		if not isinstance(date_value, basestring):
			date_value = formatdate(date_value, localtime=True)
		# Encode it here to avoid this:
		# Date: =?utf-8?q?Sat=2C_01_Sep_2012_13=3A08=3A29_-0300?=
		return native(date_value)
721137
function(seconds){
      var now, deadline;
      now = new Date();
      deadline = new Date();

      // Convert back to milliseconds by multiplying by 1000
      deadline.setTime(seconds * 1000);

      return parseInt( deadline.getTime() / 3600000 - now.getTime() / 3600000);
    }
751256
def _x_format(self):
        """"""

        def date_to_str(x):
            d = datetime.utcfromtimestamp(x).date()
            return self.x_value_formatter(d)

        return date_to_str