Compiler helper method: attempt to compile constant into object representing
    datetime object to enable relations and thus simple comparisons using Python
    operators.
357914
def compile_datetime(rule):
    
    if isinstance(rule.value, datetime.datetime):
        return rule
    try:
        # Try numeric type
        return DatetimeRule(datetime.datetime.fromtimestamp(float(rule.value)))
    except (TypeError, ValueError):
        pass
    # Try RFC3339 timestamp string
    res = TIMESTAMP_RE.match(str(rule.value))
    if res is not None:
        year, month, day, hour, minute, second = (int(n or 0) for n in res.group(*range(1, 7)))
        us_str = (res.group(7) or "0")[:6].ljust(6, "0")
        us_int = int(us_str)
        zonestr = res.group(8)
        zonespl = (0, 0) if zonestr in ['z', 'Z'] else [int(i) for i in zonestr.split(":")]
        zonediff = datetime.timedelta(minutes = zonespl[0]*60+zonespl[1])
        return DatetimeRule(datetime.datetime(year, month, day, hour, minute, second, us_int) - zonediff)
    raise ValueError("Wrong datetime format '{}'".format(rule.value))
196273
def python_cast(self, v):
        

        if self.type_is_time():
            dt = dateutil.parser.parse(v)

            if self.datatype == Column.DATATYPE_TIME:
                dt = dt.time()
            if not isinstance(dt, self.python_type):
                raise TypeError('{} was parsed to {}, expected {}'.format(v, type(dt), self.python_type))

            return dt
        else:
            # This isn't calling the python_type method -- it's getting a python type, then instantialting it,
            # such as "int(v)"
            return self.python_type(v)
1203032
def isdatetime(value):
    
    if isinstance(value, np.ndarray):
        return (value.dtype.kind == "M" or
                (value.dtype.kind == "O" and len(value) and
                 isinstance(value[0], datetime_types)))
    else:
        return isinstance(value, datetime_types)
997970
def dateTime(arg):
  
  l = len(arg)
  if l is 1:
    dt = arg[0]
    typed = type(dt)
    if typed is datetime.datetime:
      return dt
    if typed in (tuple, list) and len(dt) in [5, 6, 7]:
      return datetime.datetime(*dt)
  if l is 2:
    date = time = None
    typeArg0 = type(arg[0])
    typeArg1 = type(arg[1])
    if typeArg0 in STR_TYPES:
      return datetime.datetime.strptime(arg[0], arg[1])
    if typeArg0 is datetime.date:
      d = arg[0]
      date = [d.year, d.month, d.day]
    if typeArg0 in (tuple, list):
      date = arg[0]
    if typeArg1 is datetime.time:
      t = arg[1]
      time = [t.hour, t.minute, t.second, t.microsecond]
    if typeArg1 in (tuple, list):
      time = arg[1]
    return datetime.datetime(*date + time)
1033079
def is_np_datetime_like(dtype: Union[str, np.dtype]) -> bool:
    
    return (np.issubdtype(dtype, np.datetime64) or
            np.issubdtype(dtype, np.timedelta64))
69181
def _cast_to_type(self, value):
        
        if isinstance(value, datetime.datetime):
            return value.date()
        if isinstance(value, datetime.date):
            return value
        try:
            value = date_parser(value)
            return value.date()
        except ValueError:
            self.fail('invalid', value=value)
645088
def to_datetime(value):
    """"""
    if value is None:
        return None

    if isinstance(value, six.integer_types):
        return parser.parse(value)
    return parser.isoparse(value)
569748
def greater_than(self, greater_than):
        

        if hasattr(greater_than, 'strftime'):
            greater_than = datetime_as_utc(greater_than).strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(greater_than, six.string_types):
            raise QueryTypeError('Expected value of type `int` or instance of `datetime`, not %s' % type(greater_than))

        return self._add_condition('>', greater_than, types=[int, str])
965560
def to_datetime(arg):
    


    if isinstance(arg, datetime.datetime):
        return arg
    elif arg == 0:
        return datetime.datetime.now()
    elif isinstance(arg, str):
        if arg == "now":
            arg = datetime.datetime.now()
        elif arg == "?":
            arg = datetime.datetime(1970, 1, 1)
        else:
            arg = str2dt(arg)
    elif isinstance(arg, datetime.date):
        arg = date2datetime(arg)
    elif isinstance(arg, (int, float)):
        # Suppose it is a timestamp
        arg = ts2dt(arg)
    else:
        raise TypeError("Wrong type for argument 'arg': {}".format(arg.__class__.__name__))

    return arg
685170
def TAF_datetime_to_datetime_object(
    datetime_string             = None,
    datetime_for_year_and_month = None  # e.g. datetime.datetime.utcnow()
    ):

    

    if datetime_string.endswith("24"):

        datetime_string = datetime_string[:-2] + "00"

        tmp = datetime.datetime.strptime(datetime_string, "%d%H") +\
              datetime.timedelta(days = 1)

    else:

        tmp = datetime.datetime.strptime(datetime_string, "%d%H")

    return datetime.datetime(
        datetime_for_year_and_month.year,
        datetime_for_year_and_month.month,
        tmp.day,
        tmp.hour,
        tmp.minute
    )
1160445
def _int_to_datetime(expr):
    

    if isinstance(expr, SequenceExpr):
        return IntToDatetime(_input=expr, _data_type=types.datetime)
    elif isinstance(expr, Scalar):
        return IntToDatetime(_input=expr, _value_type=types.datetime)
379218
def default(self, obj):  # lint-amnesty, pylint: disable=arguments-differ, method-hidden
        

        if isinstance(obj, datetime):
            if obj.tzinfo is None:
                # Localize to UTC naive datetime objects
                obj = UTC.localize(obj)  # pylint: disable=no-value-for-parameter
            else:
                # Convert to UTC datetime objects from other timezones
                obj = obj.astimezone(UTC)
            return obj.isoformat()
        elif isinstance(obj, date):
            return obj.isoformat()

        return super(DateTimeJSONEncoder, self).default(obj)
1359131
def cast_datetime(ts, fmt=None):
    """"""
    dt = datetime.datetime.fromtimestamp(ts)
    if fmt:
        return dt.strftime(fmt)
    return dt
281883
def parse_datetime(value):
    
    if not value:
        return None
    elif isinstance(value, datetime.datetime):
        return value
    return dateutil.parser.parse(value)
821787
def fromPython(cls, python_datetime):

        ''' 
        '''

    # validate inputs
        title = 'Python datetime input for labDT.fromPython'
        if not isinstance(python_datetime, datetime):
            raise TypeError('\n%s must be a valid %s object.' % (title, datetime.__class__))
        elif not python_datetime.tzinfo:
            raise ValueError('\n%s must have a timezone.' % title)

    # construct labDT from python datetime
        dT = python_datetime.astimezone(pytz.utc)
        dt_kwargs = {
            'year': dT.year,
            'month': dT.month,
            'day': dT.day,
            'hour': dT.hour,
            'minute': dT.minute,
            'second': dT.second,
            'microsecond': dT.microsecond,
            'tzinfo': dT.tzinfo
        }
        return labDT(**dt_kwargs)
1351465
def to_date_or_datetime(value, ctx):
    
    if isinstance(value, str):
        temporal = ctx.get_date_parser().auto(value)
        if temporal is not None:
            return temporal
    elif type(value) == datetime.date:
        return value
    elif isinstance(value, datetime.datetime):
        return value.astimezone(ctx.timezone)

    raise EvaluationError("Can't convert '%s' to a date or datetime" % str(value))
854
def _safe_match_date_and_datetime(graphql_type, expected_python_types, value):
    """"""
    # Python datetime.datetime is a subclass of datetime.date,
    # but in this case, the two are not interchangeable.
    # Rather than using isinstance, we will therefore check for exact type equality.
    value_type = type(value)
    if not any(value_type == x for x in expected_python_types):
        raise GraphQLInvalidArgumentError(u'Expected value to be exactly one of '
                                          u'python types {}, but was {}: '
                                          u'{}'.format(expected_python_types, value_type, value))

    # The serialize() method of GraphQLDate and GraphQLDateTime produces the correct
    # ISO-8601 format that MATCH expects. We then simply represent it as a regular string.
    try:
        serialized_value = graphql_type.serialize(value)
    except ValueError as e:
        raise GraphQLInvalidArgumentError(e)

    return _safe_match_string(serialized_value)