Python datetime.datetime 模块,time() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用datetime.datetime.time()

项目:FlipDotWorker    作者:ArduinoHannover    | 项目源码 | 文件源码
def __preptime(self,when):
  """
  Extract information in a suitable format from when, 
  a datetime.datetime object.
  """
  # datetime days are numbered in the Gregorian calendar
  # while the calculations from NOAA are distibuted as
  # OpenOffice spreadsheets with days numbered from
  # 1/1/1900. The difference are those numbers taken for 
  # 18/12/2010
  self.day = when.toordinal()-(734124-40529)
  t=when.time()
  self.time= (t.hour + t.minute/60.0 + t.second/3600.0)/24.0

  self.timezone=0
  offset=when.utcoffset()
  if not offset is None:
   self.timezone=offset.seconds/3600.0
项目:ibstract    作者:jesseliu0    | 项目源码 | 文件源码
def timedur_to_IB(timedur: str) -> str:
    """
    Convert a user-input ambiguous time duration string to IB-style
    durationString and check validility.

    :param timedur: A user-input ambiguous time duration string,
                    like '1 min', '5days',etc.
    :returns: IB-style durationString

    """
    tdur = timedur_standardize(timedur)
    t_num = re.findall('\d+', tdur)[0]
    t_unit = tdur[-1]
    if t_unit in ['m', 'h']:
        multip = {'m': 60, 'h': 3600}[t_unit]
        t_num = str(multip * int(t_num))
        t_unit = 's'
    if t_unit in ['s', 'd', 'W', 'M', 'Y']:
        return t_num + ' ' + t_unit.upper()
    else:
        raise TypeError(
            "Invalid input time duration string: {}!".format(timedur))
项目:rc-niceties    作者:mjec    | 项目源码 | 文件源码
def from_frontend_value(key, value):
    """Returns a `SiteConfiguration` object value for the relevant `key` and
    JSON-serializable `value`, applying any transformation reversed by to_frontend_value."""
    if key == NICETIES_OPEN:
        from datetime import timedelta
        return timedelta(days=value)
    elif key == CLOSING_TIME:
        from datetime import datetime
        return datetime.strptime(value, '%H:%M').time()
    elif key == CLOSING_BUFFER:
        from datetime import timedelta
        return timedelta(minutes=value)
    elif key == CACHE_TIMEOUT:
        from datetime import timedelta
        return timedelta(seconds=value)
    elif key == INCLUDE_FACULTY:
        return value
    elif key == INCLUDE_RESIDENTS:
        return value
    else:
        raise ValueError('No such config key!')
项目:python-mysql-pool    作者:LuciferJack    | 项目源码 | 文件源码
def _DATETIME_to_python(self, value, dsc=None):
        """Connector/Python always returns naive datetime.datetime

        Connector/Python always returns naive timestamps since MySQL has
        no time zone support. Since Django needs non-naive, we need to add
        the UTC time zone.

        Returns datetime.datetime()
        """
        if not value:
            return None
        dt = MySQLConverter._DATETIME_to_python(self, value)
        if dt is None:
            return None
        if settings.USE_TZ and timezone.is_naive(dt):
            dt = dt.replace(tzinfo=timezone.utc)
        return dt
项目:importacsv    作者:rasertux    | 项目源码 | 文件源码
def _DATETIME_to_python(self, value, dsc=None):
        """Connector/Python always returns naive datetime.datetime

        Connector/Python always returns naive timestamps since MySQL has
        no time zone support. Since Django needs non-naive, we need to add
        the UTC time zone.

        Returns datetime.datetime()
        """
        if not value:
            return None
        dt = MySQLConverter._DATETIME_to_python(self, value)
        if dt is None:
            return None
        if settings.USE_TZ and timezone.is_naive(dt):
            dt = dt.replace(tzinfo=timezone.utc)
        return dt
项目:iCalVerter    作者:amsysuk    | 项目源码 | 文件源码
def __init__(self, dt):
        if not isinstance(dt, (datetime, date, timedelta, time)):
            raise ValueError('You must use datetime, date, timedelta or time')
        if isinstance(dt, datetime):
            self.params = Parameters({'value': 'DATE-TIME'})
        elif isinstance(dt, date):
            self.params = Parameters({'value': 'DATE'})
        elif isinstance(dt, time):
            self.params = Parameters({'value': 'TIME'})

        if (isinstance(dt, datetime) or isinstance(dt, time))\
                and getattr(dt, 'tzinfo', False):
            tzinfo = dt.tzinfo
            if tzinfo is not pytz.utc and\
               (tzutc is None or not isinstance(tzinfo, tzutc)):
                # set the timezone as a parameter to the property
                tzid = tzid_from_dt(dt)
                if tzid:
                    self.params.update({'TZID': tzid})
        self.dt = dt
项目:iCalVerter    作者:amsysuk    | 项目源码 | 文件源码
def from_ical(cls, ical, timezone=None):
        if isinstance(ical, cls):
            return ical.dt
        u = ical.upper()
        if u.startswith(('P', '-P', '+P')):
            return vDuration.from_ical(ical)

        if len(ical) in (15, 16):
            return vDatetime.from_ical(ical, timezone=timezone)
        elif len(ical) == 8:
            return vDate.from_ical(ical)
        elif len(ical) in (6, 7):
            return vTime.from_ical(ical)
        else:
            raise ValueError(
                "Expected datetime, date, or time, got: '%s'" % ical
            )
项目:cuny-bdif    作者:aristotle-tek    | 项目源码 | 文件源码
def __init__(self, manager):
        # Do a delayed import to prevent possible circular import errors.
        from boto.sdb.db.model import Model
        self.model_class = Model
        self.manager = manager
        self.type_map = {bool: (self.encode_bool, self.decode_bool),
                         int: (self.encode_int, self.decode_int),
                         float: (self.encode_float, self.decode_float),
                         self.model_class: (
                            self.encode_reference, self.decode_reference
                         ),
                         Key: (self.encode_reference, self.decode_reference),
                         datetime: (self.encode_datetime, self.decode_datetime),
                         date: (self.encode_date, self.decode_date),
                         time: (self.encode_time, self.decode_time),
                         Blob: (self.encode_blob, self.decode_blob),
                         str: (self.encode_string, self.decode_string),
                      }
        if six.PY2:
            self.type_map[long] = (self.encode_long, self.decode_long)
项目:cuny-bdif    作者:aristotle-tek    | 项目源码 | 文件源码
def decode_time(self, value):
        """ converts strings in the form of HH:MM:SS.mmmmmm
            (created by datetime.time.isoformat()) to
            datetime.time objects.

            Timzone-aware strings ("HH:MM:SS.mmmmmm+HH:MM") won't
            be handled right now and will raise TimeDecodeError.
        """
        if '-' in value or '+' in value:
            # TODO: Handle tzinfo
            raise TimeDecodeError("Can't handle timezone aware objects: %r" % value)
        tmp = value.split('.')
        arg = map(int, tmp[0].split(':'))
        if len(tmp) == 2:
            arg.append(int(tmp[1]))
        return time(*arg)
项目:cuny-bdif    作者:aristotle-tek    | 项目源码 | 文件源码
def _connect(self):
        args = dict(aws_access_key_id=self.db_user,
                    aws_secret_access_key=self.db_passwd,
                    is_secure=self.enable_ssl)
        try:
            region = [x for x in boto.sdb.regions() if x.endpoint == self.db_host][0]
            args['region'] = region
        except IndexError:
            pass
        self._sdb = boto.connect_sdb(**args)
        # This assumes that the domain has already been created
        # It's much more efficient to do it this way rather than
        # having this make a roundtrip each time to validate.
        # The downside is that if the domain doesn't exist, it breaks
        self._domain = self._sdb.lookup(self.db_name, validate=False)
        if not self._domain:
            self._domain = self._sdb.create_domain(self.db_name)
项目:smart-battery-for-smart-energy-usage    作者:AnatolyPavlov    | 项目源码 | 文件源码
def transform(self, df):
        '''Transform input
        time series into a set of time series for
        each hourly-slice in a day, where each time
        series for a given hour has days as its agument.'''
        days = extract_days(df)
        day = days[0]
        next_day = days[1]
        time_intervs_in_day = []
        for i, datetime in enumerate(df.query('index >= @day and index < @next_day').index):
            if datetime.time() not in time_intervs_in_day:
                time_intervs_in_day.append(datetime.time())
        #
        df['time'] = [d.time() for i, d in enumerate(df.index)]# Adding time only column
        time_intervs_data = {} # key=time interval, values = pd.DataFrame with daily time series
        for time_intv in time_intervs_in_day:
            time_intervs_data[time_intv] = df[df['time']==time_intv].drop('time', axis=1)
        #
        return time_intervs_data
项目:smart-battery-for-smart-energy-usage    作者:AnatolyPavlov    | 项目源码 | 文件源码
def transform_inverse(self, df):
        price = pd.read_csv(self.path_to_price, parse_dates=True, index_col='Unnamed: 0')
        #
        index = []
        values = []
        days = extract_days(df)
        time_intervs_in_day = [d.time() for i, d in enumerate(price.index)]
        for day in days:
            i = 0
            for time_intv in time_intervs_in_day:
                if time_intv <= df.index[i].time():
                    values.append(df.values[i][0])
                    index.append(datetime.combine(day, time_intv))
                else:
                    i+=1
                    values.append(df.values[i][0])
                    index.append(datetime.combine(day, time_intv))
        df_out = pd.DataFrame(values, columns=[df.columns[0]], index=index)
        return df_out
项目:chronophore    作者:mesbahamin    | 项目源码 | 文件源码
def sign_out(entry, time_out=None, forgot=False):
    """Sign out of an existing entry in the timesheet. If the user
    forgot to sign out, flag the entry.

    :param entry: `models.Entry` object. The entry to sign out.
    :param time_out: (optional) `datetime.time` object. Specify the sign out time.
    :param forgot: (optional) If true, user forgot to sign out. Entry will be flagged as forgotten.
    :return: The signed out entry.
    """ # noqa
    if time_out is None:
        time_out = datetime.today().time()

    if forgot:
        entry.forgot_sign_out = True
        logger.info(
            '{} forgot to sign out on {}.'.format(entry.user_id, entry.date)
        )

    else:
        entry.time_out = time_out

    logger.info('{} ({}) signed out.'.format(entry.user_id, entry.user_type))
    return entry
项目:learneveryword    作者:karan    | 项目源码 | 文件源码
def __init__(self, manager):
        # Do a delayed import to prevent possible circular import errors.
        from boto.sdb.db.model import Model
        self.model_class = Model
        self.manager = manager
        self.type_map = {bool: (self.encode_bool, self.decode_bool),
                         int: (self.encode_int, self.decode_int),
                         float: (self.encode_float, self.decode_float),
                         self.model_class: (
                            self.encode_reference, self.decode_reference
                         ),
                         Key: (self.encode_reference, self.decode_reference),
                         datetime: (self.encode_datetime, self.decode_datetime),
                         date: (self.encode_date, self.decode_date),
                         time: (self.encode_time, self.decode_time),
                         Blob: (self.encode_blob, self.decode_blob),
                         str: (self.encode_string, self.decode_string),
                      }
        if six.PY2:
            self.type_map[long] = (self.encode_long, self.decode_long)
项目:learneveryword    作者:karan    | 项目源码 | 文件源码
def decode_time(self, value):
        """ converts strings in the form of HH:MM:SS.mmmmmm
            (created by datetime.time.isoformat()) to
            datetime.time objects.

            Timzone-aware strings ("HH:MM:SS.mmmmmm+HH:MM") won't
            be handled right now and will raise TimeDecodeError.
        """
        if '-' in value or '+' in value:
            # TODO: Handle tzinfo
            raise TimeDecodeError("Can't handle timezone aware objects: %r" % value)
        tmp = value.split('.')
        arg = map(int, tmp[0].split(':'))
        if len(tmp) == 2:
            arg.append(int(tmp[1]))
        return time(*arg)
项目:learneveryword    作者:karan    | 项目源码 | 文件源码
def _connect(self):
        args = dict(aws_access_key_id=self.db_user,
                    aws_secret_access_key=self.db_passwd,
                    is_secure=self.enable_ssl)
        try:
            region = [x for x in boto.sdb.regions() if x.endpoint == self.db_host][0]
            args['region'] = region
        except IndexError:
            pass
        self._sdb = boto.connect_sdb(**args)
        # This assumes that the domain has already been created
        # It's much more efficient to do it this way rather than
        # having this make a roundtrip each time to validate.
        # The downside is that if the domain doesn't exist, it breaks
        self._domain = self._sdb.lookup(self.db_name, validate=False)
        if not self._domain:
            self._domain = self._sdb.create_domain(self.db_name)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def snap(self, freq='S'):
        """
        Snap time stamps to nearest occurring frequency

        """
        # Superdumb, punting on any optimizing
        freq = to_offset(freq)

        snapped = np.empty(len(self), dtype=_NS_DTYPE)

        for i, v in enumerate(self):
            s = v
            if not freq.onOffset(s):
                t0 = freq.rollback(s)
                t1 = freq.rollforward(s)
                if abs(s - t0) < abs(t1 - s):
                    s = t0
                else:
                    s = t1
            snapped[i] = s

        # we know it conforms; skip check
        return DatetimeIndex(snapped, freq=freq, verify_integrity=False)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def test_datetime_time(self):
        # test support for datetime.time
        df = DataFrame([time(9, 0, 0), time(9, 1, 30)], columns=["a"])
        df.to_sql('test_time', self.conn, index=False)
        res = read_sql_table('test_time', self.conn)
        tm.assert_frame_equal(res, df)

        # GH8341
        # first, use the fallback to have the sqlite adapter put in place
        sqlite_conn = TestSQLiteFallback.connect()
        sql.to_sql(df, "test_time2", sqlite_conn, index=False)
        res = sql.read_sql_query("SELECT * FROM test_time2", sqlite_conn)
        ref = df.applymap(lambda _: _.strftime("%H:%M:%S.%f"))
        tm.assert_frame_equal(ref, res)  # check if adapter is in place
        # then test if sqlalchemy is unaffected by the sqlite adapter
        sql.to_sql(df, "test_time3", self.conn, index=False)
        if self.flavor == 'sqlite':
            res = sql.read_sql_query("SELECT * FROM test_time3", self.conn)
            ref = df.applymap(lambda _: _.strftime("%H:%M:%S.%f"))
            tm.assert_frame_equal(ref, res)
        res = sql.read_sql_table("test_time3", self.conn)
        tm.assert_frame_equal(df, res)
项目:vityBot    作者:GDGVIT    | 项目源码 | 文件源码
def _is_between(check_time, start_time, end_time):
        """
        check if a given time is between an interval
        :param check_time: datetime.time obj
        :param start_time: datetime.time obj
        :param end_time: datetime.time obj
        :return:
        """
        if start_time.hour < check_time.hour < end_time.hour:
            return True
        elif check_time.hour == start_time.hour and check_time.hour < \
                end_time.hour:
            return check_time.minute >= start_time.minute
        elif check_time.hour > start_time.hour and check_time.hour == \
                end_time.hour:
            return check_time.minute <= end_time.minute
        elif check_time.hour == start_time.hour and check_time.hour == \
                end_time.hour:
            return start_time.minute <= check_time.minute <= end_time.minute
        else:
            return False
项目:vityBot    作者:GDGVIT    | 项目源码 | 文件源码
def next_class(self, time):
        """
        get the class next to a given time
        :param time: datetime.time object
        :return: [course, course time]
        """
        day = datetime.now().weekday()
        weekdays = ['monday', 'tuesday', 'wednesday',
                    'thursday', 'friday']
        courses = self.all_classes(weekdays[day])

        for c in courses:
            if self._is_before(time, c[duration][0]):
                # return the first class that follows given time
                return c
        # no class after given time
        return None
项目:python-caltrain    作者:ownaginatious    | 项目源码 | 文件源码
def _resolve_time(t):
    """
    Resolves the time string into datetime.time. This method
    is needed because Caltrain arrival/departure time hours
    can exceed 23 (e.g. 24, 25), to signify trains that arrive
    after 12 AM. The 'day' variable is incremented from 0 in
    these situations, and the time resolved back to a valid
    datetime.time (e.g. 24:30:00 becomes days=1, 00:30:00).

    :param t: the time to resolve
    :type t: str or unicode

    :returns: tuple of days and datetime.time
    """
    hour, minute, second = [int(x) for x in t.split(":")]
    day, hour = divmod(hour, 24)
    r = _BASE_DATE + timedelta(hours=hour,
                               minutes=minute,
                               seconds=second)
    return day, r.time()
项目:python-caltrain    作者:ownaginatious    | 项目源码 | 文件源码
def _resolve_duration(start, end):
    """
    Resolves the duration between two times. Departure/arrival
    times that exceed 24 hours or cross a day boundary are correctly
    resolved.

    :param start: the time to resolve
    :type start: Stop
    :param end: the time to resolve
    :type end: Stop

    :returns: tuple of days and datetime.time
    """
    start_time = _BASE_DATE + timedelta(hours=start.departure.hour,
                                        minutes=start.departure.minute,
                                        seconds=start.departure.second,
                                        days=start.departure_day)
    end_time = _BASE_DATE + timedelta(hours=end.arrival.hour,
                                      minutes=end.arrival.minute,
                                      seconds=end.arrival.second,
                                      days=end.departure_day)
    return end_time - start_time
项目:snowflake-connector-python    作者:snowflakedb    | 项目源码 | 文件源码
def _pre_TIMESTAMP_LTZ_to_python(self, value, ctx):
        """
        TIMESTAMP LTZ to datetime

        This takes consideration of the session parameter TIMEZONE if
        available. If not, tzlocal is used
        """
        microseconds, fraction_of_nanoseconds = \
            self._extract_timestamp(value, ctx)
        tzinfo_value = self._get_session_tz()

        try:
            t0 = ZERO_EPOCH + timedelta(seconds=(microseconds))
            t = pytz.utc.localize(t0, is_dst=False).astimezone(tzinfo_value)
            return t, fraction_of_nanoseconds
        except OverflowError:
            logger.debug(
                "OverflowError in converting from epoch time to "
                "timestamp_ltz: %s(ms). Falling back to use struct_time."
            )
            return time.gmtime(microseconds), fraction_of_nanoseconds
项目:snowflake-connector-python    作者:snowflakedb    | 项目源码 | 文件源码
def _TIME_to_python(self, ctx):
        """
        TIME to formatted string, SnowflakeDateTime, or datetime.time

        No timezone is attached.
        """

        scale = ctx['scale']

        conv0 = lambda value: datetime.utcfromtimestamp(float(value)).time()

        def conv(value):
            microseconds = float(value[0:-scale + 6])
            return datetime.utcfromtimestamp(microseconds).time()

        return conv if scale > 6 else conv0
项目:snowflake-connector-python    作者:snowflakedb    | 项目源码 | 文件源码
def _derive_offset_timestamp(self, value, is_utc=False):
        """
        Derives TZ offset and timestamp from the datatime object
        """
        tzinfo = value.tzinfo
        if tzinfo is None:
            # If no tzinfo is attached, use local timezone.
            tzinfo = self._get_session_tz() if not is_utc else pytz.UTC
            t = pytz.utc.localize(value, is_dst=False).astimezone(tzinfo)
        else:
            # if tzinfo is attached, just covert to epoch time
            # as the server expects it in UTC anyway
            t = value
        offset = tzinfo.utcoffset(
            t.replace(tzinfo=None)).total_seconds() / 60 + 1440
        return offset, t
项目:alfred-ec2    作者:SoMuchToGrok    | 项目源码 | 文件源码
def __init__(self, manager):
        # Do a delayed import to prevent possible circular import errors.
        from boto.sdb.db.model import Model
        self.model_class = Model
        self.manager = manager
        self.type_map = {bool: (self.encode_bool, self.decode_bool),
                         int: (self.encode_int, self.decode_int),
                         float: (self.encode_float, self.decode_float),
                         self.model_class: (
                            self.encode_reference, self.decode_reference
                         ),
                         Key: (self.encode_reference, self.decode_reference),
                         datetime: (self.encode_datetime, self.decode_datetime),
                         date: (self.encode_date, self.decode_date),
                         time: (self.encode_time, self.decode_time),
                         Blob: (self.encode_blob, self.decode_blob),
                         str: (self.encode_string, self.decode_string),
                      }
        if six.PY2:
            self.type_map[long] = (self.encode_long, self.decode_long)
项目:alfred-ec2    作者:SoMuchToGrok    | 项目源码 | 文件源码
def decode_time(self, value):
        """ converts strings in the form of HH:MM:SS.mmmmmm
            (created by datetime.time.isoformat()) to
            datetime.time objects.

            Timzone-aware strings ("HH:MM:SS.mmmmmm+HH:MM") won't
            be handled right now and will raise TimeDecodeError.
        """
        if '-' in value or '+' in value:
            # TODO: Handle tzinfo
            raise TimeDecodeError("Can't handle timezone aware objects: %r" % value)
        tmp = value.split('.')
        arg = map(int, tmp[0].split(':'))
        if len(tmp) == 2:
            arg.append(int(tmp[1]))
        return time(*arg)
项目:alfred-ec2    作者:SoMuchToGrok    | 项目源码 | 文件源码
def _connect(self):
        args = dict(aws_access_key_id=self.db_user,
                    aws_secret_access_key=self.db_passwd,
                    is_secure=self.enable_ssl)
        try:
            region = [x for x in boto.sdb.regions() if x.endpoint == self.db_host][0]
            args['region'] = region
        except IndexError:
            pass
        self._sdb = boto.connect_sdb(**args)
        # This assumes that the domain has already been created
        # It's much more efficient to do it this way rather than
        # having this make a roundtrip each time to validate.
        # The downside is that if the domain doesn't exist, it breaks
        self._domain = self._sdb.lookup(self.db_name, validate=False)
        if not self._domain:
            self._domain = self._sdb.create_domain(self.db_name)
项目:RemoteTree    作者:deNULL    | 项目源码 | 文件源码
def isoformat(self, sep='T'):
        """
        Formats the date as "%Y-%m-%d %H:%M:%S" with the sep param between the
        date and time portions

        :param set:
            A single character of the separator to place between the date and
            time

        :return:
            The formatted datetime as a unicode string in Python 3 and a byte
            string in Python 2
        """

        if self.microsecond == 0:
            return self.strftime('0000-%%m-%%d%s%%H:%%M:%%S' % sep)
        return self.strftime('0000-%%m-%%d%s%%H:%%M:%%S.%%f' % sep)
项目:quickstart-git2s3    作者:aws-quickstart    | 项目源码 | 文件源码
def isoformat(self, sep='T'):
        """
        Formats the date as "%Y-%m-%d %H:%M:%S" with the sep param between the
        date and time portions

        :param set:
            A single character of the separator to place between the date and
            time

        :return:
            The formatted datetime as a unicode string in Python 3 and a byte
            string in Python 2
        """

        if self.microsecond == 0:
            return self.strftime('0000-%%m-%%d%s%%H:%%M:%%S' % sep)
        return self.strftime('0000-%%m-%%d%s%%H:%%M:%%S.%%f' % sep)
项目:jabbapylib3    作者:jabbalaci    | 项目源码 | 文件源码
def get_timestamp_from_year_to_second(separator=False, date=None):
    """A compact timestamp.

    Example: 20110523_234401 . date can be a datetime object.
    If date is not specified, the current date and time (now) will be used."""
    if date:
        now = date
    else:
        now = datetime.now()
    date = datetime.date(now)
    time = datetime.time(now)
    #return "%d-%02d-%02d @ %02dh%02d%02d" % (date.year, date.month, date.day, time.hour, time.minute, time.second)
    template = "{year}{month:02}{day:02}_{hour:02}{minute:02}{second:02}"
    if separator:
        template = "{year}_{month:02}_{day:02}_{hour:02}{minute:02}{second:02}"
    return template.format(year=date.year, month=date.month, day=date.day, hour=time.hour, minute=time.minute, second=time.second)
项目:Chorus    作者:DonaldBough    | 项目源码 | 文件源码
def _DATETIME_to_python(self, value, dsc=None):
        """Connector/Python always returns naive datetime.datetime

        Connector/Python always returns naive timestamps since MySQL has
        no time zone support. Since Django needs non-naive, we need to add
        the UTC time zone.

        Returns datetime.datetime()
        """
        if not value:
            return None
        dt = MySQLConverter._DATETIME_to_python(self, value)
        if dt is None:
            return None
        if settings.USE_TZ and timezone.is_naive(dt):
            dt = dt.replace(tzinfo=timezone.utc)
        return dt
项目:coms4156_jumpstart    作者:keirl    | 项目源码 | 文件源码
def __init__(self, cid=-1):
        self.cid = cid
        self.now = datetime.time(datetime.now())
        self.today = date.today()
        self.ds = self.get_client()
项目:FlipDotWorker    作者:ArduinoHannover    | 项目源码 | 文件源码
def sunrise(self,when=None):
  """
  return the time of sunrise as a datetime.time object
  when is a datetime.datetime object. If none is given
  a local time zone is assumed (including daylight saving
  if present)
  """
  if when is None : when = datetime.now(tz=LocalTimezone())
  self.__preptime(when)
  self.__calc()
  return sun.__timefromdecimalday(self.sunrise_t)
项目:FlipDotWorker    作者:ArduinoHannover    | 项目源码 | 文件源码
def __timefromdecimalday(day):
  """
  returns a datetime.time object.

  day is a decimal day between 0.0 and 1.0, e.g. noon = 0.5
  """
  hours  = 24.0*day
  h      = int(hours)
  minutes= (hours-h)*60
  m      = int(minutes)
  seconds= (minutes-m)*60
  s      = int(seconds)
  return time(hour=h,minute=m,second=s)
项目:FlipDotWorker    作者:ArduinoHannover    | 项目源码 | 文件源码
def __calc(self):
  """
  Perform the actual calculations for sunrise, sunset and
  a number of related quantities.

  The results are stored in the instance variables
  sunrise_t, sunset_t and solarnoon_t
  """
  timezone = self.timezone # in hours, east is positive
  longitude= self.long     # in decimal degrees, east is positive
  latitude = self.lat      # in decimal degrees, north is positive

  time  = self.time # percentage past midnight, i.e. noon  is 0.5
  day      = self.day     # daynumber 1=1/1/1900

  Jday     =day+2415018.5+time-timezone/24 # Julian day
  Jcent    =(Jday-2451545)/36525    # Julian century

  Manom    = 357.52911+Jcent*(35999.05029-0.0001537*Jcent)
  Mlong    = 280.46646+Jcent*(36000.76983+Jcent*0.0003032)%360
  Eccent   = 0.016708634-Jcent*(0.000042037+0.0001537*Jcent)
  Mobliq   = 23+(26+((21.448-Jcent*(46.815+Jcent*(0.00059-Jcent*0.001813))))/60)/60
  obliq    = Mobliq+0.00256*cos(rad(125.04-1934.136*Jcent))
  vary     = tan(rad(obliq/2))*tan(rad(obliq/2))
  Seqcent  = sin(rad(Manom))*(1.914602-Jcent*(0.004817+0.000014*Jcent))+sin(rad(2*Manom))*(0.019993-0.000101*Jcent)+sin(rad(3*Manom))*0.000289
  Struelong= Mlong+Seqcent
  Sapplong = Struelong-0.00569-0.00478*sin(rad(125.04-1934.136*Jcent))
  declination = deg(asin(sin(rad(obliq))*sin(rad(Sapplong))))

  eqtime   = 4*deg(vary*sin(2*rad(Mlong))-2*Eccent*sin(rad(Manom))+4*Eccent*vary*sin(rad(Manom))*cos(2*rad(Mlong))-0.5*vary*vary*sin(4*rad(Mlong))-1.25*Eccent*Eccent*sin(2*rad(Manom)))

  hourangle= deg(acos(cos(rad(90.833))/(cos(rad(latitude))*cos(rad(declination)))-tan(rad(latitude))*tan(rad(declination))))

  self.solarnoon_t=(720-4*longitude-eqtime+timezone*60)/1440
  self.sunrise_t  =self.solarnoon_t-hourangle*4/1440
  self.sunset_t   =self.solarnoon_t+hourangle*4/1440
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def testUnknownOffsets(self):
        # This tzinfo behavior is required to make
        # datetime.time.{utcoffset, dst, tzname} work as documented.

        dst_tz = pytz.timezone('US/Eastern')

        # This information is not known when we don't have a date,
        # so return None per API.
        self.assertTrue(dst_tz.utcoffset(None) is None)
        self.assertTrue(dst_tz.dst(None) is None)
        # We don't know the abbreviation, but this is still a valid
        # tzname per the Python documentation.
        self.assertEqual(dst_tz.tzname(None), 'US/Eastern')
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def testHourBefore(self):
        # Python's datetime library has a bug, where the hour before
        # a daylight savings transition is one hour out. For example,
        # at the end of US/Eastern daylight savings time, 01:00 EST
        # occurs twice (once at 05:00 UTC and once at 06:00 UTC),
        # whereas the first should actually be 01:00 EDT.
        # Note that this bug is by design - by accepting this ambiguity
        # for one hour one hour per year, an is_dst flag on datetime.time
        # became unnecessary.
        self._test_all(
                self.transition_time - timedelta(hours=1), self.after
                )
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def test_belfast(self):
        # Belfast uses London time.
        self.assertTrue('Europe/Belfast' in pytz.all_timezones_set)
        self.assertFalse('Europe/Belfast' in pytz.common_timezones)
        self.assertFalse('Europe/Belfast' in pytz.common_timezones_set)
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def __init__(self, activates, from_tzinfo, to_tzinfo, reference_date=None):
        #: the time of the activation of the timezone transition in UTC.
        self.activates = activates
        #: the timezone from where the transition starts.
        self.from_tzinfo = from_tzinfo
        #: the timezone for after the transition.
        self.to_tzinfo = to_tzinfo
        #: the reference date that was provided.  This is the `dt` parameter
        #: to the :func:`get_next_timezone_transition`.
        self.reference_date = reference_date
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def format_date(date=None, format='medium', locale=LC_TIME):
    """Return a date formatted according to the given pattern.

    >>> d = date(2007, 04, 01)
    >>> format_date(d, locale='en_US')
    u'Apr 1, 2007'
    >>> format_date(d, format='full', locale='de_DE')
    u'Sonntag, 1. April 2007'

    If you don't want to use the locale default formats, you can specify a
    custom date pattern:

    >>> format_date(d, "EEE, MMM d, ''yy", locale='en')
    u"Sun, Apr 1, '07"

    :param date: the ``date`` or ``datetime`` object; if `None`, the current
                 date is used
    :param format: one of "full", "long", "medium", or "short", or a custom
                   date/time pattern
    :param locale: a `Locale` object or a locale identifier
    """
    if date is None:
        date = date_.today()
    elif isinstance(date, datetime):
        date = date.date()

    locale = Locale.parse(locale)
    if format in ('full', 'long', 'medium', 'short'):
        format = get_date_format(format, locale=locale)
    pattern = parse_pattern(format)
    return pattern.apply(date, locale)
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def parse_time(string, locale=LC_TIME):
    """Parse a time from a string.

    This function uses the time format for the locale as a hint to determine
    the order in which the time fields appear in the string.

    >>> parse_time('15:30:00', locale='en_US')
    datetime.time(15, 30)

    :param string: the string containing the time
    :param locale: a `Locale` object or a locale identifier
    :return: the parsed time
    :rtype: `time`
    """
    # TODO: try ISO format first?
    format = get_time_format(locale=locale).pattern.lower()
    hour_idx = format.index('h')
    if hour_idx < 0:
        hour_idx = format.index('k')
    min_idx = format.index('m')
    sec_idx = format.index('s')

    indexes = [(hour_idx, 'H'), (min_idx, 'M'), (sec_idx, 'S')]
    indexes.sort()
    indexes = dict([(item[1], idx) for idx, item in enumerate(indexes)])

    # FIXME: support 12 hour clock, and 0-based hour specification
    #        and seconds should be optional, maybe minutes too
    #        oh, and time-zones, of course

    numbers = re.findall('(\d+)', string)
    hour = int(numbers[indexes['H']])
    minute = int(numbers[indexes['M']])
    second = int(numbers[indexes['S']])
    return time(hour, minute, second)
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def __init__(self, value, locale):
        assert isinstance(value, (date, datetime, time))
        if isinstance(value, (datetime, time)) and value.tzinfo is None:
            value = value.replace(tzinfo=UTC)
        self.value = value
        self.locale = Locale.parse(locale)
项目:my-weather-indicator    作者:atareao    | 项目源码 | 文件源码
def is_day_now(sunrise, sunset, rawOffset):
    now = datetime.time(datetime.utcnow() + timedelta(hours=rawOffset))
    hora = ('%s:%s') % (now.hour, now.minute)
    if time_is_lower(sunset, sunrise):
        # The sunset actually occurs on the next day based on UTC
        if time_is_lower(hora, sunrise) and time_is_upper(hora, sunset):
            return False
    else:
        if time_is_lower(hora, sunrise) or time_is_upper(hora, sunset):
            return False
    return True
项目:my-weather-indicator    作者:atareao    | 项目源码 | 文件源码
def timeformat(hhmm, AMPM=False):
    """
    This method converts time in 24h format to 12h format
    Example:   "00:32" is "12:32 AM"
    "13:33" is "01:33 PM"
    """

    hh, mm = hhmm.split(":")
    if cf.s2f(mm) == 60.0:
        hh = str(int(cf.s2f(hh) + 1.0))
        hhmm = hh + ':00'
    if AMPM:
        ampm = hhmm.split(":")
        if (len(ampm) == 0) or (len(ampm) > 3):
            return hhmm
        # is AM? from [00:00, 12:00[
        hour = int(ampm[0]) % 24
        isam = (hour >= 0) and (hour < 12)
        # 00:32 should be 12:32 AM not 00:32
        if isam:
            ampm[0] = ('12' if (hour == 0) else "%02d" % (hour))
        else:
            ampm[0] = ('12' if (hour == 12) else "%02d" % (hour - 12))
        return ': '.join(ampm) + (' AM' if isam else ' PM')
    else:
        return hhmm
项目:ibstract    作者:jesseliu0    | 项目源码 | 文件源码
def tzcomb(dt1: datetime, dt2: datetime.time, tz: datetime.tzinfo):
    return tz.localize(datetime.combine(dt1, dt2))
项目:ibstract    作者:jesseliu0    | 项目源码 | 文件源码
def barsize_to_IB(barsize: str) -> str:
    """
    Convert a user-input ambiguous bar size string to IB-style barSizeSetting
    and check validility.

    :param barsize: A user-input ambiguous time duration string,
                    like '1 min', '5days',etc.
    :returns: IB-style barSizeSetting

    """
    timedur = timedur_standardize(barsize)
    IB_barsize_map = {
        '1s': '1 secs',
        '5s': '5 secs',
        '10s': '10 secs',
        '15s': '15 secs',
        '30s': '30 secs',
        '1m': '1 min',
        '2m': '2 mins',
        '3m': '3 mins',
        '5m': '5 mins',
        '10m': '10 mins',
        '15m': '15 mins',
        '20m': '20 mins',
        '30m': '30 mins',
        '1h': '1 hour',
        '2h': '2 hours',
        '3h': '3 hours',
        '4h': '4 hours',
        '8h': '8 hours',
        '1d': '1 day',
        '1W': '1W',
        '1M': '1M'
    }
    try:
        barSizeSetting = IB_barsize_map[timedur]
    except KeyError:
        raise KeyError("Invalid input barsize string: {}!".format(barsize))
    return barSizeSetting
项目:ibstract    作者:jesseliu0    | 项目源码 | 文件源码
def trading_days(
        time_end: datetime, time_dur: str=None, time_start: datetime=None):
    """determine start and end trading days covering time_dur or time_start.
       So far use NYSE trading days calendar for all exchanges.
    """
    xchg_tz = time_end.tzinfo
    end_idx = bisect.bisect_left(NYSE_CAL, time_end.replace(tzinfo=None))
    if time_start is not None:
        # ignore time_dur, use time_start, time_end as boundary.
        start_idx = bisect.bisect_left(
            NYSE_CAL, time_start.replace(tzinfo=None))
        trading_days = NYSE_CAL[start_idx:end_idx]
    else:
        tdur = timedur_to_timedelta(time_dur)
        # If tdur remainding h/m/s > 0, round it up to 1 more day.
        n_trading_days = tdur.days
        if xchg_tz.normalize(
                time_end - relativedelta(seconds=tdur.seconds)
        ) < tzmin(time_end, tz=xchg_tz):
            n_trading_days += 1
        # time_dur in days, and time_end is not beginning of day.
        if time_end.time() != datetime.min.time():
            n_trading_days += 1
        # Slicing from trading day calendar.
        trading_days = NYSE_CAL[end_idx-n_trading_days:end_idx]
    return trading_days
项目:rc-niceties    作者:mjec    | 项目源码 | 文件源码
def set_to_default():
    import datetime
    set(NICETIES_OPEN, datetime.timedelta(days=14))
    set(CLOSING_TIME, datetime.time(18, 0))
    set(CLOSING_BUFFER, datetime.timedelta(minutes=30))
    set(CACHE_TIMEOUT, datetime.timedelta(days=7))
    set(INCLUDE_FACULTY, False)
    set(INCLUDE_RESIDENTS, False)
    db.session.commit()
项目:python-mysql-pool    作者:LuciferJack    | 项目源码 | 文件源码
def adapt_datetime_with_timezone_support(value):
    # Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL.
    if settings.USE_TZ:
        if timezone.is_naive(value):
            warnings.warn("MySQL received a naive datetime (%s)"
                          " while time zone support is active." % value,
                          RuntimeWarning)
            default_timezone = timezone.get_default_timezone()
            value = timezone.make_aware(value, default_timezone)
        value = value.astimezone(timezone.utc).replace(tzinfo=None)
    if HAVE_CEXT:
        return datetime_to_mysql(value)
    else:
        return value.strftime("%Y-%m-%d %H:%M:%S.%f")