Fix the conversion of Date/Time values.
 :nodoc:
490484
def cast_value(v)
      return nil if v.nil?
      if @type == :date
        self.style = STYLE_DATE if self.style == 0
        v
      elsif (@type == :time && v.is_a?(Time)) || (@type == :time && v.respond_to?(:to_time))
        self.style = STYLE_DATE if self.style == 0
        # one simple little fix.  I DO NOT WANT TIME IN LOCAL TIME!
        unless v.is_a?(Time)
          v = v.respond_to?(:to_time) ? v.to_time : v
        end
        v
      elsif @type == :float
        v.to_f
      elsif @type == :integer
        v.to_i
      elsif @type == :boolean
        v ? 1 : 0
      elsif @type == :iso_8601
        #consumer is responsible for ensuring the iso_8601 format when specifying this type
        v
      else
        @type = :string
        # TODO find a better way to do this as it accounts for 30% of
        # processing time in benchmarking...
        Axlsx::trust_input ? v.to_s : ::CGI.escapeHTML(v.to_s)
      end
    end
267433
def toDatetime(value, format=None):
    
    if value and value is not None:
        if format:
            value = datetime.strptime(value, format)
        else:
            # https://bugs.python.org/issue30684
            # And platform support for before epoch seems to be flaky.
            # TODO check for others errors too.
            if int(value) == 0:
                value = 86400
            value = datetime.fromtimestamp(int(value))
    return value
162121
def to_date(value, default=None):
    
    if isinstance(value, DateTime):
        return value
    if not value:
        if default is None:
            return None
        return to_date(default)
    try:
        if isinstance(value, str) and '.' in value:
            # https://docs.plone.org/develop/plone/misc/datetime.html#datetime-problems-and-pitfalls
            return DateTime(value, datefmt='international')
        return DateTime(value)
    except (TypeError, ValueError, DateTimeError):
        return to_date(default)
418762
def restore(self, value, context=None):
        
        value = super(DatetimeWithTimezoneColumn, self).restore(value, context)

        if value in ('today', 'now'):
            value = datetime.date.now()

        if isinstance(value, datetime.datetime):
            tz = pytz.timezone(context.timezone)

            if tz is not None:
                if value.tzinfo is None:
                    base_tz = pytz.timezone(orb.system.settings().server_timezone)

                    # the machine timezone and preferred timezone match, so create off utc time
                    if base_tz == tz:
                        value = tz.fromutc(value)

                    # convert the server timezone to a preferred timezone
                    else:
                        value = base_tz.fromutc(value).astimezone(tz)
                else:
                    value = value.astimezone(tz)
            else:
                log.warning('No local timezone defined')

        return value
367202
def date_and_delta(value):
    """"""
    now = _now()
    if isinstance(value, datetime):
        date = value
        delta = now - value
    elif isinstance(value, timedelta):
        date = now - value
        delta = value
    else:
        try:
            value = int(value)
            delta = timedelta(seconds=value)
            date = now - delta
        except (ValueError, TypeError):
            return (None, value)
    return date, abs_timedelta(delta)
97596
def parse_date(value: Union[date, StrIntFloat]) -> date:
    
    if isinstance(value, date):
        if isinstance(value, datetime):
            return value.date()
        else:
            return value

    number = get_numeric(value)
    if number is not None:
        return from_unix_seconds(number).date()

    match = date_re.match(cast(str, value))
    if not match:
        raise errors.DateError()

    kw = {k: int(v) for k, v in match.groupdict().items()}

    with change_exception(errors.DateError, ValueError):
        return date(**kw)
1254793
def cast_datetime_filter(value):
    
    if isinstance(value, str):
        dtime = parse_datetime(value)

    elif isinstance(value, datetime):
        dtime = value
    else:
        raise ValueError('Received value of type {0}'.format(type(value)))

    return dtime.isoformat()
924928
def naturaltime(val):
    """"""
    val = val.replace(tzinfo=pytz.utc) \
        if isinstance(val, datetime) else parse(val)
    now = datetime.utcnow().replace(tzinfo=pytz.utc)

    return humanize.naturaltime(now - val)
296817
def check_time_param(t):
    """"""

    if type(t) is str:
        if not ISO.match(t):
            raise ValueError('Date string "%s" does not match ISO8601 format' %
                             (t))
        return t
    else:
        return t.isoformat()
747003
def values(self, dtype, dates, sids):
        
        shape = (len(dates), len(sids))
        return {
            datetime64ns_dtype: self._datetime_values,
            float64_dtype: self._float_values,
            int64_dtype: self._int_values,
            bool_dtype: self._bool_values,
            object_dtype: self._object_values,
        }[dtype](shape)
1369244
def fix_timedelta_repr(func):
    
    # We don't need to do anything if we're not on 3.7 or above
    if version < (3, 7):
        return func

    def fix_timedelta(match):
        values = match.group(1).split(", ")
        param_repr = ", ".join(
            "{}={}".format(param, value)
            for param, value in zip(("days", "seconds", "microseconds"), values)
            if value != "0"
        )

        # If we have a zero length timedelta it should be represented as
        # timedelta(0), i.e. without named parameters
        if not param_repr:
            param_repr = "0"

        return "timedelta({})".format(param_repr)

    func.__doc__ = re.sub(r"timedelta\(([^)]+)\)", fix_timedelta, func.__doc__)
    return func
265954
def _try_convert_to_date(self, data):
        

        # no conversion on empty
        if not len(data):
            return data, False

        new_data = data
        if new_data.dtype == 'object':
            try:
                new_data = data.astype('int64')
            except:
                pass

        # ignore numbers that are out of range
        if issubclass(new_data.dtype.type, np.number):
            in_range = (isnull(new_data.values) | (new_data > self.min_stamp) |
                        (new_data.values == iNaT))
            if not in_range.all():
                return data, False

        date_units = (self.date_unit,) if self.date_unit else self._STAMP_UNITS
        for date_unit in date_units:
            try:
                new_data = to_datetime(new_data, errors='raise',
                                       unit=date_unit)
            except ValueError:
                continue
            except:
                break
            return new_data, True
        return data, False
554596
def normalize_time(timestamp):
    """"""
    offset = timestamp.utcoffset()
    if offset is None:
        return timestamp
    return timestamp.replace(tzinfo=None) - offset
315622
def display_value(time)
      case time
      when nil       then '-'
      when 0...1     then '%0ims' % (time * 1000)
      when 1...60    then '%0.02fs' % time
      when 60...3600 then '%dm%02ds' % [time / 60, (time % 60).round]
      else                '%dh%02dm%02ds' % [time / 3600, (time % 3600) / 60, (time % 60).round]
      end
    end
989707
def np_datetime64_compat(s, *args, **kwargs):
    
    s = tz_replacer(s)
    return np.datetime64(s, *args, **kwargs)
641624
def fix_mispelled_day(cls, timestr):
        
        day_extraction = cls.START_WITH_DAY_OF_WEEK.match(timestr)
        if day_extraction is not None:
            day = day_extraction.group(1).lower()
            if len(day) == 3:
                dataset = DAYS_ABBR
            else:
                dataset = DAYS
            if day not in dataset:
                days = list(dataset)
                days.sort(key=lambda e: levenshtein(day, e))
                return days[0] + day_extraction.group(2)
352506
def convert_datetime(value, parameter):
    '''
    
    '''
    value = _check_default(value, parameter, ( '', '-', None ))
    if value is None or isinstance(value, datetime.datetime):
        return value
    for fmt in settings.DATETIME_INPUT_FORMATS:
        try:
            return datetime.datetime.strptime(value, fmt)
        except (ValueError, TypeError):
            continue
    raise ValueError("`{}` does not match a format in settings.DATETIME_INPUT_FORMATS".format(value))