Add UTC to datetime-naive and convert to UTC for datetime aware

    input: python datetime (naive, utc, non-utc) or Numpy datetime64  #FIXME add Pandas and AstroPy time classes
    output: utc datetime
165164
def forceutc(t: Union[str, datetime.datetime, datetime.date, np.datetime64]) -> Union[datetime.datetime, datetime.date]:
    
    # need to passthrough None for simpler external logic.
# %% polymorph to datetime
    if isinstance(t, str):
        t = parse(t)
    elif isinstance(t, np.datetime64):
        t = t.astype(datetime.datetime)
    elif isinstance(t, datetime.datetime):
        pass
    elif isinstance(t, datetime.date):
        return t
    elif isinstance(t, (np.ndarray, list, tuple)):
        return np.asarray([forceutc(T) for T in t])
    else:
        raise TypeError('datetime only input')
# %% enforce UTC on datetime
    if t.tzinfo is None:  # datetime-naive
        t = t.replace(tzinfo=UTC)
    else:  # datetime-aware
        t = t.astimezone(UTC)  # changes timezone, preserving absolute time. E.g. noon EST = 5PM UTC

    return t
963403
def to_utc(some_time):
    

    # Convert timezone aware objects to UTC
    if some_time.tzinfo and some_time.utcoffset():
        some_time = some_time.astimezone(tzutc())

    # Now that time is UTC, simply remove the timezone component.
    return some_time.replace(tzinfo=None)
741648
def _build_time(time, kwargs):
    
    tz = kwargs.pop('tz', 'UTC')
    if time:
        if kwargs:
            raise ValueError('Cannot pass kwargs and a time')
        else:
            return ensure_utc(time, tz)
    elif not kwargs:
        raise ValueError('Must pass a time or kwargs')
    else:
        return datetime.time(**kwargs)
504326
def _datetime_to_utc(self, dt):
        """"""

        if not dt.tzinfo:
            dt = dt.replace(tzinfo=tz.gettz())
        return dt.astimezone(tz.gettz('UTC'))
89364
def _try_assign_utc_time(self, raw_time, time_base):
        """"""

        # Check if the raw time is encoded UTC since y2k or just uptime
        if raw_time != IOTileEvent.InvalidRawTime and (raw_time & (1 << 31)):
            y2k_offset = self.raw_time ^ (1 << 31)
            return self._Y2KReference + datetime.timedelta(seconds=y2k_offset)

        if time_base is not None:
            return time_base + datetime.timedelta(seconds=raw_time)

        return None
880972
def set_timezone(data, tz=None, from_local=False):
    
    # pandas object?
    if isinstance(data, pd.DataFrame) | isinstance(data, pd.Series):
        try:
            try:
                data.index = data.index.tz_convert(tz)
            except Exception as e:
                if from_local:
                    data.index = data.index.tz_localize(
                        get_timezone()).tz_convert(tz)
                else:
                    data.index = data.index.tz_localize('UTC').tz_convert(tz)
        except Exception as e:
            pass

    # not pandas...
    else:
        if isinstance(data, str):
            data = parse_date(data)
        try:
            try:
                data = data.astimezone(tz)
            except Exception as e:
                data = timezone('UTC').localize(data).astimezone(timezone(tz))
        except Exception as e:
            pass

    return data
1070787
def new_datetime(klass = DateTime)
      datetime = klass.jd(JD_EPOCH + ((@value.to_r + @sub_second) / 86400))
      @utc_offset && @utc_offset != 0 ? datetime.new_offset(Rational(@utc_offset, 86400)) : datetime
    end
796930
def SetTimezone(self, timezone):
    
    if not timezone:
      return

    try:
      self._timezone = pytz.timezone(timezone)
    except pytz.UnknownTimeZoneError:
      raise ValueError('Unsupported timezone: {0:s}'.format(timezone))
526678
def _add_nat(self):
        
        if is_period_dtype(self):
            raise TypeError('Cannot add {cls} and {typ}'
                            .format(cls=type(self).__name__,
                                    typ=type(NaT).__name__))

        # GH#19124 pd.NaT is treated like a timedelta for both timedelta
        # and datetime dtypes
        result = np.zeros(len(self), dtype=np.int64)
        result.fill(iNaT)
        return type(self)(result, dtype=self.dtype, freq=None)
363499
def utc_to_local(utc_dt):
    
    # get integer timestamp to avoid precision lost
    timestamp = calendar.timegm(utc_dt.timetuple())
    local_dt = datetime.datetime.fromtimestamp(timestamp)
    assert utc_dt.resolution >= datetime.timedelta(microseconds=1)
    return local_dt.replace(microsecond=utc_dt.microsecond)
81825
def naive(
    year, month, day, hour=0, minute=0, second=0, microsecond=0
):  # type: (int, int, int, int, int, int, int) -> DateTime
    
    return DateTime(year, month, day, hour, minute, second, microsecond)
780411
def value_as_datetime(self):
        ''' 

        '''
        if self.value is None:
            return None
        v1, v2 = self.value
        if isinstance(v1, numbers.Number):
            d1 = datetime.utcfromtimestamp(v1 / 1000)
        else:
            d1 = v1
        if isinstance(v2, numbers.Number):
            d2 = datetime.utcfromtimestamp(v2 / 1000)
        else:
            d2 = v2
        return d1, d2
858672
def add_hours(self, datetimestr, n):
        
        a_datetime = self.parse_datetime(datetimestr)
        return a_datetime + timedelta(seconds=3600 * n)
119197
def make_naive(dt):
    
    tt = dt.utctimetuple()
    ts = calendar.timegm(tt)
    local_tt = time.localtime(ts)
    return datetime.datetime(*local_tt[:6])
107980
def to_timestamp(dt, timestamp):
  
  if dt.tzinfo:
    # this is an "aware" datetime with an explicit timezone. Throw an error.
    raise TypeError('Cannot store a timezone aware datetime. '
                    'Convert to UTC and store the naive datetime.')
  timestamp.seconds = calendar.timegm(dt.timetuple())
  timestamp.nanos = dt.microsecond * _NANOS_PER_MICRO
538572
def convert_to_utc(time):
        

        # time is already in UTC
        if 'Z' in time:
            return time
        else:
            time_formatted = time[:-3] + time[-2:]
            dt = datetime.strptime(time_formatted, '%Y-%m-%dT%H:%M:%S%z')
            dt = dt.astimezone(timezone('UTC'))
            return dt.strftime('%Y-%m-%dT%H:%M:%SZ')
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))