Convert a PyEphem Date into a timezone aware python datetime
321496
def _ephem_to_timezone(date, tzinfo):
    # utility from unreleased PyEphem 3.6.7.1
    """""""
    seconds, microseconds = _ephem_convert_to_seconds_and_microseconds(date)
    date = dt.datetime.fromtimestamp(seconds, tzinfo)
    date = date.replace(microsecond=microseconds)
    return date
1213200
def adjust_datetime_to_timezone(value, from_tz, to_tz=None):
    
    if to_tz is None:
        to_tz = settings.TIME_ZONE
    if value.tzinfo is None:
        if not hasattr(from_tz, "localize"):
            from_tz = pytz.timezone(smart_str(from_tz))
        value = from_tz.localize(value)
    return value.astimezone(pytz.timezone(smart_str(to_tz)))
131800
def _decode_datetime(obj):
    """"""

    if '__datetime__' in obj:
        obj = datetime.datetime.strptime(obj['as_str'].decode(), "%Y%m%dT%H:%M:%S.%f")
    return obj
619222
def datetime(self, start: int = 2000, end: int = 2035,
                 timezone: Optional[str] = None) -> DateTime:
        
        datetime_obj = datetime.combine(
            date=self.date(start, end),
            time=self.time(),
        )
        if timezone:
            if not pytz:
                raise ImportError('Timezones are supported only with pytz')
            tz = pytz.timezone(timezone)
            datetime_obj = tz.localize(datetime_obj)

        return datetime_obj
1045962
def asdatetime(self, naive=True):
    
    args = list(self.timetuple()[0:6])+[self.microsecond]
    if not naive:
      args.append(self.tzinfo)
    return datetime.datetime(*args)
611238
def datetime_to_djd(time):
    

    if time.tzinfo is None:
        time_utc = pytz.utc.localize(time)
    else:
        time_utc = time.astimezone(pytz.utc)

    djd_start = pytz.utc.localize(dt.datetime(1899, 12, 31, 12))
    djd = (time_utc - djd_start).total_seconds() * 1.0/(60 * 60 * 24)

    return djd
1001158
def add_timezone(value, tz=None):
    
    tz = tz or timezone.get_current_timezone()
    try:
        if timezone.is_naive(value):
            return timezone.make_aware(value, tz)
    except AttributeError:  # 'datetime.date' object has no attribute 'tzinfo'
        dt = datetime.datetime.combine(value, datetime.time())
        return timezone.make_aware(dt, tz)
    return value
821212
def ensure_timezone(dateTime,timeZone=None):
    '''
    
    '''

    if is_aware(dateTime) and not getattr(settings,'USE_TZ',False):
        return make_naive(dateTime,timezone=timeZone)
    if is_naive(dateTime) and getattr(settings,'USE_TZ',False):
        return make_aware(dateTime,timezone=timeZone)
    # If neither condition is met, then we can return what was passed
    return dateTime
1144068
def timestamp_to_datetime(response):
    ""
    if not response:
        return None
    try:
        response = int(response)
    except ValueError:
        return None
    return datetime.datetime.fromtimestamp(response)
942893
def parse_timestamp(timestamp):
    """"""
    dt = dateutil.parser.parse(timestamp)
    return dt.astimezone(dateutil.tz.tzutc())
489329
def get_as_datetime(self, key):
        
        value = self.get(key)
        return DateTimeConverter.to_datetime(value)
234396
def timestamp_to_datetime(cls, time_stamp, localized=True):
        
        ret = datetime.datetime.utcfromtimestamp(time_stamp)
        if localized:
            ret = localize(ret, pytz.utc)
        return ret
1098190
def str_to_datetime(timestamp, str_format='%Y-%m-%d_%H:%M:%S.fff'):
    
    date_time = datetime.strptime(timestamp.split('.')[0],
                                  str_format.split('.')[0])
    if '.' in timestamp:
        date_time += timedelta(seconds=eval('0.%s' % timestamp.split('.')[1]))
    if DEFAULT_TIMEZONE_AWARE:
        date_time = date_time.replace(
            tzinfo=psycopg2.tz.FixedOffsetTimezone(
                offset=DEFAULT_TIMEZONE * 60, name=None))
    return date_time
247039
def convert_timestamp(timestamp):
    
    datetime = dt.datetime.utcfromtimestamp(timestamp/1000.)
    return np.datetime64(datetime.replace(tzinfo=None))
31006
def dictlist_convert_to_datetime(dict_list: Iterable[Dict],
                                 key: str,
                                 datetime_format_string: str) -> None:
    
    for d in dict_list:
        d[key] = datetime.datetime.strptime(d[key], datetime_format_string)
270655
def _build_date_time_time_zone(self, date_time):
        
        timezone = date_time.tzinfo.zone if date_time.tzinfo is not None else None
        return {
            self._cc('dateTime'): date_time.strftime('%Y-%m-%dT%H:%M:%S'),
            self._cc('timeZone'): get_windows_tz(timezone or self.protocol.timezone)
        }
1263304
def convert_timezone(date_str, tz_from, tz_to="UTC", fmt=None):
    
    tz_offset = datetime_to_timezone(
        datetime.datetime.now(), tz=tz_from).strftime('%z')
    tz_offset = tz_offset[:3] + ':' + tz_offset[3:]

    date = parse_date(str(date_str) + tz_offset)
    if tz_from != tz_to:
        date = datetime_to_timezone(date, tz_to)

    if isinstance(fmt, str):
        return date.strftime(fmt)
    return date