Formats datetime to take less room when it is recent
187334
def datetime_f(dttm):
    """"""
    if dttm:
        dttm = dttm.isoformat()
        now_iso = datetime.now().isoformat()
        if now_iso[:10] == dttm[:10]:
            dttm = dttm[11:]
        elif now_iso[:4] == dttm[:4]:
            dttm = dttm[5:]
    return '<nobr>{}</nobr>'.format(dttm)
189499
def date_time_string(timestamp=None):
    """"""
    global _last_date_time_string
    _last_timestamp, _last_str = _last_date_time_string
    if timestamp is None:
        timestamp = time.time()
    _curr_timestamp = int(timestamp)
    if _curr_timestamp == _last_timestamp:
        return _last_str
    else:
        year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
        s = b"%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
                weekdayname[wd],
                day, monthname[month], year,
                hh, mm, ss)
        _last_date_time_string = (_curr_timestamp, s)
        return s
192539
def datetime2ole(dt):
    """"""
    delta = dt - OLE_TIME_ZERO
    delta_float = delta / datetime.timedelta(days=1)  # trick from SO
    return delta_float
601913
def pretty_date(time=False):
    
    now = datetime.now(PST_TIMEZONE)
    if type(time) is int:
        diff = now - datetime.fromtimestamp(time)
    elif isinstance(time, datetime):
        diff = now - time
    elif not time:
        diff = now - now
    second_diff = diff.seconds
    day_diff = diff.days

    if day_diff < 0:
        return ''

    if day_diff == 0:
        if second_diff < 10:
            return "just now"
        if second_diff < 60:
            return str(second_diff) + " seconds ago"
        if second_diff < 120:
            return "a minute ago"
        if second_diff < 3600:
            return str(int(second_diff / 60)) + " minutes ago"
        if second_diff < 7200:
            return "an hour ago"
        if second_diff < 86400:
            return str(int(second_diff / 3600)) + " hours ago"
    if day_diff == 1:
        return "Yesterday"
    if day_diff < 7:
        return str(day_diff) + " days ago"
    if day_diff < 31:
        return str(int(day_diff / 7)) + " weeks ago"
    if day_diff < 365:
        return str(int(day_diff / 30)) + " months ago"
    return str(int(day_diff / 365)) + " years ago"
410244
def _normalize(parsed, **options):
    
    if options.get("exact"):
        return parsed

    if isinstance(parsed, time):
        now = options["now"] or datetime.now()

        return datetime(
            now.year,
            now.month,
            now.day,
            parsed.hour,
            parsed.minute,
            parsed.second,
            parsed.microsecond,
        )
    elif isinstance(parsed, date) and not isinstance(parsed, datetime):
        return datetime(parsed.year, parsed.month, parsed.day)

    return parsed
553026
def _serialize_datetime(value):
    """"""
    if not isinstance(value, (datetime, arrow.Arrow)):
        raise ValueError(u'The received object was not a datetime: '
                         u'{} {}'.format(type(value), value))
    return value.isoformat()
1293722
def str2dt(s):
    """"""
    return datetime.datetime.strptime(s, _FMTS if s.count(":") == 2 else _FMT if s.count(":") == 1 else _FMT0)
999326
function formatTime(time) {
				if (time == '') {
					if (settings.required) return settings.duration ? '0:00' : '00:00';
					else return time;
				}
				if ((new RegExp('^(-|\\+)?([0-9]+)(.([0-9]{1,2})?)?$', 'i')).test(time)) {
					var hour = parseInt(RegExp.$2);
					var min = parseInt(RegExp.$4);
					if (!min) min = 0;
					var negative = settings.duration && settings.durationNegative && RegExp.$1 == '-' ? true : false;
					if (hour >= 24 && !settings.duration) hour = hour % 24;
					if (min >= 60) min = min % 60;
					if (settings.precision != 1) {
						var f = Math.floor(min / settings.precision);
						min = f * settings.precision + (Math.round((min - f * settings.precision) / settings.precision) == 1 ? settings.precision : 0);
						if (min >= 60) min = 0;
					}
					time = (negative ? '-' : '') + (hour < 10 && !settings.duration ? '0' : '') + hour + settings.separator + (RegExp.$3 ? (min < 10 ? '0' : '') + min : '00');
				}
				else if ((new RegExp('^(-|\\+)?.([0-9]{1,2})')).test(time)) {
					var min = parseInt(RegExp.$2);
					var negative = settings.duration && settings.durationNegative && RegExp.$1 == '-' ? true : false;
					if (min >= 60) min = min % 60;
					time = (negative && min > 0 ? '-' : '') + '0' + (!settings.duration ? '0' : '') + settings.separator + (min < 10 ? '0' : '') + min;
				}
				else {
					time = '0' + (!settings.duration ? '0' : '') + settings.separator + '00';
				}
				return (settings.duration && settings.useDurationPlusSign && !time.match(/^\-/) && !time.match(/^0+:00$/) ? '+' : '') + time;
			}
792106
def formatTime(self, record, datefmt=None):  # noqa
        
        if datefmt:
            s = datetime.datetime.now().strftime(datefmt)
        else:
            t = datetime.datetime.now().strftime(self.default_time_format)
            s = self.default_msec_format % (t, record.msecs)
        return s
18838
def format_item(x, timedelta_format=None, quote_strings=True):
    """"""
    if isinstance(x, (np.datetime64, datetime)):
        return format_timestamp(x)
    if isinstance(x, (np.timedelta64, timedelta)):
        return format_timedelta(x, timedelta_format=timedelta_format)
    elif isinstance(x, (str, bytes)):
        return repr(x) if quote_strings else x
    elif isinstance(x, (float, np.float)):
        return '{0:.4}'.format(x)
    else:
        return str(x)
649792
def date_to_datetime(d):
    
    if not isinstance(d, datetime):
        d = datetime.combine(d, datetime.min.time())
    return d
47496
def clean(date, ignore_time=False):
        
        # Return empty input immediately.
        if not date:
            return date

        parts = re.split(r'[\-/. ]', date)

        if (len(parts) == 3) or \
                (len(parts) > 3 and ignore_time) or \
                (len(parts) == 4 and re.match(r'^[0:]*$', parts[3])) or \
                (len(parts) == 5 and re.match(r'^[0:]*$', parts[3]) and re.match(r'^0*$', parts[4])):
            if len(parts[0]) == 4 and len(parts[1]) <= 2 and len(parts[2]) <= 2:
                # Assume date is in  YYYY-MM-DD of YYYY-M-D format.
                return parts[0] + '-' + ('00' + parts[1])[-2:] + '-' + ('00' + parts[2])[-2:]

            if len(parts[0]) <= 2 and len(parts[1]) <= 2 and len(parts[2]) == 4:
                # Assume date is in  DD-MM-YYYY or D-M-YYYY format.
                return parts[2] + '-' + ('00' + parts[1])[-2:] + '-' + ('00' + parts[0])[-2:]

            if len(parts[0]) <= 2 and len(parts[1]) <= 2 and len(parts[2]) == 2:
                # Assume date is in  DD-MM-YY or D-M-YY format.
                year = '19' + parts[2] if parts[2] >= '20' else '20' + parts[2]

                return year + '-' + ('00' + parts[1])[-2:] + '-' + ('00' + parts[0])[-2:]

        # Try DDmonYYYY or DDmonYYYY HH:mm:ss format
        pattern = r'^(\d{2})([a-z]{3})(\d{4})' + ('.*$' if ignore_time else r'(\D(\d{1,2})\D(\d{1,2})\D(\d{1,2}))?$')
        match = re.match(pattern, date.lower())
        if match and match.group(2) in DateCleaner.month_map:
            ret = match.group(3) + '-' + DateCleaner.month_map[match.group(2)] + '-' + match.group(1)
            if len(match.groups()) == 7 and match.group(4):
                ret += 'T' + match.group(5) + ':' + match.group(6) + ':' + match.group(7)
            return ret

        # Try YYYYMMDD format.
        pattern = r'^\d{8}' + ('.*$' if ignore_time else '$')
        match = re.match(pattern, date)
        if match:
            # Assume date is YYYYMMDD format
            return date[0:4] + '-' + date[4:6] + '-' + date[6:8]

        # Format not recognized. Just return the original string.
        return date
1117951
function getColonTime(timeString) {
  var totalSeconds = 0;
  var timeValues = [
    1,
    1 * 60,
    1 * 60 * 60,
    1 * 60 * 60 * 24,
    1 * 60 * 60 * 24 * 7,
  ];
  var timePairs = timeString.split(':');
  for (var i = 0; i < timePairs.length; i++) {
    totalSeconds += parseInt(timePairs[i], 10) * timeValues[timePairs.length - i - 1];
  }
  return totalSeconds;
}
1359120
def formatTime (self, record, datefmt=None):
        """"""
        if datefmt is None:
            datefmt = '%Y-%m-%d %H:%M:%S'

        ct = self.converter(record.created)
        t  = time.strftime(datefmt, ct)
        s  = '%s.%03d' % (t, record.msecs)

        return s
1339784
def datetime(self):
        """"""
        if not self._datetime_calculated:
            self._datetime_calculated = True

            # if no datetime after 10 tokens, break to avoid parsing
            # very long lines
            split_tokens = self.split_tokens[:10]

            for offs in range(len(split_tokens)):
                dt = self._match_datetime_pattern(split_tokens[offs:offs + 4])
                if dt:
                    self._datetime = dt
                    self._datetime_nextpos = offs
                    if self._datetime_format.startswith("iso8601"):
                        self._datetime_nextpos += 1
                    else:
                        self._datetime_nextpos += 4

                    # separate datetime str and linestr
                    self._line_str = (' '.join(self.split_tokens
                                               [self._datetime_nextpos:]))

                    if self.level:
                        self._datetime_nextpos += 2

                    self._reformat_timestamp(self._datetime_format)
                    break

        return self._datetime
554596
def normalize_time(timestamp):
    """"""
    offset = timestamp.utcoffset()
    if offset is None:
        return timestamp
    return timestamp.replace(tzinfo=None) - offset
724261
void formatMinutes(StringBuilder b, ZonedDateTime d, int width) {
    zeroPad2(b, d.getMinute(), width);
  }