Turn obj.value into a timedelta or datetime.
354255
def transformToNative(obj):
        
        if obj.isNative:
            return obj
        value = getattr(obj, 'value_param', 'DURATION').upper()
        if hasattr(obj, 'value_param'):
            del obj.value_param
        if obj.value == '':
            obj.isNative = True
            return obj
        elif value  == 'DURATION':
            try:
                return Duration.transformToNative(obj)
            except ParseError:
                logger.warning("TRIGGER not recognized as DURATION, trying "
                             "DATE-TIME, because iCal sometimes exports "
                             "DATE-TIMEs without setting VALUE=DATE-TIME")
                try:
                    obj.isNative = False
                    dt = DateTimeBehavior.transformToNative(obj)
                    return dt
                except:
                    msg = "TRIGGER with no VALUE not recognized as DURATION " \
                          "or as DATE-TIME"
                    raise ParseError(msg)
        elif value == 'DATE-TIME':
            # TRIGGERs with DATE-TIME values must be in UTC, we could validate
            # that fact, for now we take it on faith.
            return DateTimeBehavior.transformToNative(obj)
        else:
            raise ParseError("VALUE must be DURATION or DATE-TIME")
186781
def duration_to_timedelta(obj):
    
    matches = DURATION_PATTERN.search(obj)
    matches = matches.groupdict(default="0")
    matches = {k: int(v) for k, v in matches.items()}
    return timedelta(**matches)
1190875
def _serialize(self, value, attr, obj):
        
        if value is None:
            return None

        if self.use_isoformat:
            return datetime.utcfromtimestamp(value).isoformat()
        else:
            return value
768209
def _converter(self, value):
        """"""
        if not isinstance(value, datetime.date):
            raise TypeError('{0} is not valid date'.format(value))
        return value
901160
def value(self, value, *args, **kwargs):
        
        from datetime import datetime
        value = self.obj.value(value, *args, **kwargs)
        try:
            rv = datetime.strptime(value, self.format)
        except ValueError as _:  # noqa
            rv = None
        return rv
5750
def _serialize(self, value, attr, obj, **kwargs):
        """"""
        if value is None:
            return None

        return int(datetime_to_timestamp(value))
298929
function(obj)
    {
        return (/Date/).test(Object.prototype.toString.call(obj)) && !isNaN(obj.getTime());
    }
957254
protected function extractDatetimeValue($obj_property)
    {
        // Attempt to retain microsecond precision
        return \DateTime::createFromFormat(
            self::DATETIME_FORMAT_UDOTU,
            sprintf('%0.6F', bcdiv($obj_property->getTimestampMicrosecondsValue(), self::MICROSECONDS))
        );

        // Works, to seconds only
        // return (new \DateTime())->setTimestamp($obj_property->getTimestampMicrosecondsValue() / self::MICROSECONDS);
    }
882867
function convertToTimestamp(value) {
    if (value instanceof Date) {
      return value.getTime();
    } else if (typeof value === 'number') {
      return Math.floor(value);
    } else if (typeof value === 'string') {
      return Date.parse(value);
    } else {
      return NaN;
    }
  }
584583
def to_datetime(timestamp):
    """"""
    return dt.fromtimestamp(time.mktime(
        time.localtime(int(str(timestamp)[:10]))))
1154057
def clean_up_datetime(obj_map):
    """"""
    clean_map = {}
    for key, value in obj_map.items():
        if isinstance(value, datetime.datetime):
            clean_map[key] = {
                'year': value.year,
                'month': value.month,
                'day': value.day,
                'hour': value.hour,
                'minute': value.minute,
                'second': value.second,
                'microsecond': value.microsecond,
                'tzinfo': value.tzinfo
            }
        elif isinstance(value, dict):
            clean_map[key] = clean_up_datetime(value)
        elif isinstance(value, list):
            if key not in clean_map:
                clean_map[key] = []
            if len(value) > 0:
                for index, list_value in enumerate(value):
                    if isinstance(list_value, dict):
                        clean_map[key].append(clean_up_datetime(list_value))
                    else:
                        clean_map[key].append(list_value)
            else:
                clean_map[key] = value
        else:
            clean_map[key] = value
    return clean_map
973588
def prepare_arg(value):
    
    if value is None:
        return value
    elif isinstance(value, (list, dict)) or hasattr(value, 'to_python'):
        return json.dumps(_normalize(value))
    elif isinstance(value, datetime.timedelta):
        now = datetime.datetime.now()
        return int((now + value).timestamp())
    elif isinstance(value, datetime.datetime):
        return round(value.timestamp())
    elif isinstance(value, LazyProxy):
        return str(value)
    return value
310024
def maybe_cast_to_datetime(value, dtype, errors='raise'):
    
    from pandas.core.tools.timedeltas import to_timedelta
    from pandas.core.tools.datetimes import to_datetime

    if dtype is not None:
        if isinstance(dtype, str):
            dtype = np.dtype(dtype)

        is_datetime64 = is_datetime64_dtype(dtype)
        is_datetime64tz = is_datetime64tz_dtype(dtype)
        is_timedelta64 = is_timedelta64_dtype(dtype)

        if is_datetime64 or is_datetime64tz or is_timedelta64:

            # Force the dtype if needed.
            msg = ("The '{dtype}' dtype has no unit. "
                   "Please pass in '{dtype}[ns]' instead.")

            if is_datetime64 and not is_dtype_equal(dtype, _NS_DTYPE):
                if dtype.name in ('datetime64', 'datetime64[ns]'):
                    if dtype.name == 'datetime64':
                        raise ValueError(msg.format(dtype=dtype.name))
                    dtype = _NS_DTYPE
                else:
                    raise TypeError("cannot convert datetimelike to "
                                    "dtype [{dtype}]".format(dtype=dtype))
            elif is_datetime64tz:

                # our NaT doesn't support tz's
                # this will coerce to DatetimeIndex with
                # a matching dtype below
                if is_scalar(value) and isna(value):
                    value = [value]

            elif is_timedelta64 and not is_dtype_equal(dtype, _TD_DTYPE):
                if dtype.name in ('timedelta64', 'timedelta64[ns]'):
                    if dtype.name == 'timedelta64':
                        raise ValueError(msg.format(dtype=dtype.name))
                    dtype = _TD_DTYPE
                else:
                    raise TypeError("cannot convert timedeltalike to "
                                    "dtype [{dtype}]".format(dtype=dtype))

            if is_scalar(value):
                if value == iNaT or isna(value):
                    value = iNaT
            else:
                value = np.array(value, copy=False)

                # have a scalar array-like (e.g. NaT)
                if value.ndim == 0:
                    value = iNaT

                # we have an array of datetime or timedeltas & nulls
                elif np.prod(value.shape) or not is_dtype_equal(value.dtype,
                                                                dtype):
                    try:
                        if is_datetime64:
                            value = to_datetime(value, errors=errors)
                            # GH 25843: Remove tz information since the dtype
                            # didn't specify one
                            if value.tz is not None:
                                value = value.tz_localize(None)
                            value = value._values
                        elif is_datetime64tz:
                            # The string check can be removed once issue #13712
                            # is solved. String data that is passed with a
                            # datetime64tz is assumed to be naive which should
                            # be localized to the timezone.
                            is_dt_string = is_string_dtype(value)
                            value = to_datetime(value, errors=errors).array
                            if is_dt_string:
                                # Strings here are naive, so directly localize
                                value = value.tz_localize(dtype.tz)
                            else:
                                # Numeric values are UTC at this point,
                                # so localize and convert
                                value = (value.tz_localize('UTC')
                                         .tz_convert(dtype.tz))
                        elif is_timedelta64:
                            value = to_timedelta(value, errors=errors)._values
                    except (AttributeError, ValueError, TypeError):
                        pass

        # coerce datetimelike to object
        elif is_datetime64_dtype(value) and not is_datetime64_dtype(dtype):
            if is_object_dtype(dtype):
                if value.dtype != _NS_DTYPE:
                    value = value.astype(_NS_DTYPE)
                ints = np.asarray(value).view('i8')
                return tslib.ints_to_pydatetime(ints)

            # we have a non-castable dtype that was passed
            raise TypeError('Cannot cast datetime64 to {dtype}'
                            .format(dtype=dtype))

    else:

        is_array = isinstance(value, np.ndarray)

        # catch a datetime/timedelta that is not of ns variety
        # and no coercion specified
        if is_array and value.dtype.kind in ['M', 'm']:
            dtype = value.dtype

            if dtype.kind == 'M' and dtype != _NS_DTYPE:
                value = value.astype(_NS_DTYPE)

            elif dtype.kind == 'm' and dtype != _TD_DTYPE:
                value = to_timedelta(value)

        # only do this if we have an array and the dtype of the array is not
        # setup already we are not an integer/object, so don't bother with this
        # conversion
        elif not (is_array and not (issubclass(value.dtype.type, np.integer) or
                                    value.dtype == np.object_)):
            value = maybe_infer_to_datetimelike(value)

    return value
1065602
def _datetime_to_json(value):
    """"""
    if isinstance(value, datetime.datetime):
        value = value.strftime(_RFC3339_MICROS_NO_ZULU)
    return value
10028
def _encode_datetime(obj):
    """"""

    if isinstance(obj, datetime.datetime):
        obj = {'__datetime__': True, 'as_str': obj.strftime("%Y%m%dT%H:%M:%S.%f").encode()}
    return obj
399668
def string_to_datetime(self, obj):
        
        if isinstance(obj, six.string_types) and len(obj) == 19:
            try:
                return datetime.strptime(obj, "%Y-%m-%dT%H:%M:%S")
            except ValueError:
                pass
        if isinstance(obj, six.string_types) and len(obj) > 19:
            try:
                return datetime.strptime(obj, "%Y-%m-%dT%H:%M:%S.%f")
            except ValueError:
                pass
        if isinstance(obj, six.string_types) and len(obj) == 10:
            try:
                return datetime.strptime(obj, "%Y-%m-%d")
            except ValueError:
                pass
        return obj
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)