python类time()的实例源码

dateandtime.py 文件源码 项目:jabbapylib3 作者: jabbalaci 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)
base.py 文件源码 项目:Chorus 作者: DonaldBough 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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
courses_model.py 文件源码 项目:coms4156_jumpstart 作者: keirl 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def __init__(self, cid=-1):
        self.cid = cid
        self.now = datetime.time(datetime.now())
        self.today = date.today()
        self.ds = self.get_client()
sunrise.py 文件源码 项目:FlipDotWorker 作者: ArduinoHannover 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)
sunrise.py 文件源码 项目:FlipDotWorker 作者: ArduinoHannover 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
sunrise.py 文件源码 项目:FlipDotWorker 作者: ArduinoHannover 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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
test_tzinfo.py 文件源码 项目:sndlatr 作者: Schibum 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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')
test_tzinfo.py 文件源码 项目:sndlatr 作者: Schibum 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
                )
test_tzinfo.py 文件源码 项目:sndlatr 作者: Schibum 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
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)
dates.py 文件源码 项目:sndlatr 作者: Schibum 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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
dates.py 文件源码 项目:sndlatr 作者: Schibum 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)
dates.py 文件源码 项目:sndlatr 作者: Schibum 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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)
dates.py 文件源码 项目:sndlatr 作者: Schibum 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
weatherservice.py 文件源码 项目:my-weather-indicator 作者: atareao 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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
weatherservice.py 文件源码 项目:my-weather-indicator 作者: atareao 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
utils.py 文件源码 项目:ibstract 作者: jesseliu0 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def tzcomb(dt1: datetime, dt2: datetime.time, tz: datetime.tzinfo):
    return tz.localize(datetime.combine(dt1, dt2))
utils.py 文件源码 项目:ibstract 作者: jesseliu0 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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
utils.py 文件源码 项目:ibstract 作者: jesseliu0 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
config.py 文件源码 项目:rc-niceties 作者: mjec 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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()
base.py 文件源码 项目:python-mysql-pool 作者: LuciferJack 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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")


问题


面经


文章

微信
公众号

扫码关注公众号