python类today()的实例源码

frontend_s3.py 文件源码 项目:miracle 作者: mozilla 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def upload(processor, data):
    user_token = data['user']
    today = date.today()
    blob = json.dumps(data, separators=(',', ':')).encode('utf-8')
    blob = gzip.compress(blob, 7)
    name = 'v2/sessions/%s/%s/%s/%s.json.gz' % (
        today.year, today.month, user_token, uuid.uuid1().hex)
    try:
        processor.bucket.put(
            name, blob,
            ContentEncoding='gzip',
            ContentType='application/json')
    except ClientError:  # pragma: no cover
        processor.raven.captureException()
        return False

    return True
util.py 文件源码 项目:ci_scripts 作者: twotwo 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def __init__(self, ini_file, dry_run=False):
        self.dry_run = dry_run

        self.build_info = []
        self.logger = logging.getLogger('util.agentBuilder')

        import ConfigParser
        # config = ConfigParser.RawConfigParser(allow_no_value=True)
        config = ConfigParser.ConfigParser()
        config.read(ini_file)
        root_dir = config.get('base', 'root_dir')

        self.lib_base_dir = config.get('base', 'lib_base_dir', 0, {'root_dir': root_dir})
        self.channels_dir = config.get('base', 'channels_dir', 0, {'root_dir': root_dir})

        self.demo_dir = config.get('demo', 'demo_dir', 0, {'root_dir': root_dir})
        from datetime import date
        self.apk_dir = config.get('demo', 'apk_dir', 0, {'root_dir': root_dir, 'day':date.today().strftime('%m%d')})

        self.plugin_dir = config.get('plugins', 'plugin_dir', 0, {'root_dir': root_dir})
plugin.py 文件源码 项目:enigma2 作者: Openeight 项目源码 文件源码 阅读 42 收藏 0 点赞 0 评论 0
def CheckDate(self):
        # Check if image is not to old for update (max 30days)
        self.CheckDateDone = True
        tmpdate = getEnigmaVersionString()
        imageDate = date(int(tmpdate[0:4]), int(tmpdate[5:7]), int(tmpdate[8:10]))
        datedelay = imageDate +  timedelta(days=180)
        message = _("Your image is out of date!\n\n"
                "After such a long time, there is a risk that your %s %s will not\n"
                "boot after online-update, or will show disfunction in running Image.\n\n"
                "A new flash will increase the stability\n\n"
                "An online update is done at your own risk !!\n\n\n"
                "Do you still want to update?") % (getMachineBrand(), getMachineName())

        if datedelay > date.today():
            self.updating = True
            self.activityTimer.start(100, False)
            self.ipkg.startCmd(IpkgComponent.CMD_UPGRADE_LIST)
        else:
            print"[SOFTWAREMANAGER] Your image is to old (%s), you need to flash new !!" %getEnigmaVersionString()
            self.session.openWithCallback(self.checkDateCallback, MessageBox, message, default = False)
            return
uiObj.py 文件源码 项目:caltrac 作者: shiburizu 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def triggerUpdate(self):
        self.caluser.updateProfile(self.inp)
        self.Root.toolbar.title = "CalTrac - %s" % date.isoformat(date.today())
        self.Root.nameLbl.text = 'About ' + self.caluser.getDict('name')
        self.Root.heightLbl.text = 'Height: ' + self.caluser.getDict('height')
        self.Root.weightLbl.text = 'Weight: ' + self.caluser.getDict('weight')
        self.Root.ageLbl.text = 'Age: ' + self.caluser.getDict('age')
        if self.caluser.getDict('preg') == '0':
            self.Root.genderLbl.text = 'Gender: ' + self.caluser.getDict('gender')
            self.Root.kcalTxt.text = 'Kcal target: ' + str(int(float(self.caluser.getDict('bmr'))))
        else:
            self.Root.genderLbl.text = 'Gender: %s (Pregnant)' % self.caluser.getDict('gender') 
            self.Root.kcalTxt.text = 'Kcal target: ' + str(int(float(self.caluser.getDict('bmr')))+350) 
        self.Root.ratingLbl.text = 'Rating: ' + self.caluser.getDict('rating')
        self.nav_drawer.ids['nameBtn'].text = self.caluser.getDict('name')
        self.Profile.ids['profileToolbar'].left_action_items = [['arrow-left', lambda x: self.changeScreens('Root')]]
models.py 文件源码 项目:oscar-wagtail-demo 作者: pgovers 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
def events(self):
        # Get list of live event pages that are descendants of this page
        events = EventPage.objects.live().descendant_of(self)

        # Filter events list to get ones that are either
        # running now or start in the future
        events = events.filter(date_from__gte=date.today())

        # Order by date
        events = events.order_by('date_from')

        return events
demo_tags.py 文件源码 项目:oscar-wagtail-demo 作者: pgovers 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def event_listing_homepage(context, count=2):
    events = EventPage.objects.live()
    events = events.filter(date_from__gte=date.today()).order_by('date_from')
    return {
        'events': events[:count].select_related('feed_image'),
        # required by the pageurl tag that we want to use within this template
        'request': context['request'],
    }


# Advert snippets
export.py 文件源码 项目:scibot 作者: SciCrunch 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def export_json_impl():
    h = HypothesisUtils(username=username, token=api_token, group=group, max_results=100000)
    params = {'group' : h.group }
    rows = h.search_all(params)
    annos = [HypothesisAnnotation(row) for row in rows]

    # clean up bugs from old curation workflow
    for anno in annos:
        if anno.tags:
            new_tags = []
            for tag in anno.tags:
                if tag in bad_tags:
                    new_tags.append(tag.replace('RRID:', 'RRIDCUR:'))  # scibot made a mistake early, might be able to correct tags in bulk someday
                else:
                    new_tags.append(tag)  # horribly inefficient...
            anno.tags = new_tags

        if anno.text.startswith('RRID:'):  # catch cases where the RRID was put in text instead of in tags
            if 'RRIDCUR:Missing' in anno.tags or 'RRIDCUR:Unrecognized' in anno.tags:
                rtag = anno.text.split(None,1)[0]  # trap for cases where there is more text after an RRID...
                if rtag not in anno.tags:
                    anno.tags.append(rtag)
                    print('TEXT ISSUE for %s at https://hyp.is/%s' % (anno.user, anno.id))
        elif anno.exact and anno.exact.startswith('RRID:'):  # this needs to go second in case of RRIDCUR:Incorrect
            if anno.exact.startswith('RRID: '):  # deal with nospace first
                rtag = anno.exact.replace('RRID: ', 'RRID:')
            else:
                rtag = anno.exact
            rtag = rtag.split(None,1)[0]  # trap more
            if rtag not in anno.tags:
                if anno.user == 'scibot' and len(anno.tags) == 1 and anno.tags[0].startswith('RRID:RRID:'):  # FIXME HACK
                    anno.tags = [rtag]
                else:
                    pass  # anything else we detect in the data doesn't need to be corrected or used to fix tags

    output_json = [anno.__dict__ for anno in annos]
    DATE = date.today().strftime('%Y-%m-%d')
    return output_json, DATE

### URG
courses_model.py 文件源码 项目:coms4156_jumpstart 作者: keirl 项目源码 文件源码 阅读 42 收藏 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()
anilist.py 文件源码 项目:aniping 作者: kuruoujou 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _get_season_shows(self):
        """Gets the list of this season's shows from anilist.

        Returns:
            list. A list of shows in the anilist format. These are
            expected to be run through _get_remote_show_info, as anilist
            does not provide everything for every show in this output.
        """
        target_date = date.today()
        airing_list = requests.get("{0}/browse/anime?year={1}&season={2}&full_page=true&access_token={3}".format(self._api_url,target_date.year,self._get_season_string(),self._access_token))

        return airing_list.json()
test_validation.py 文件源码 项目:deb-python-cassandra-driver 作者: openstack 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
def test_datetime_date_support(self):
        today = date.today()
        self.DatetimeTest.objects.create(test_id=2, created_at=today)
        dt2 = self.DatetimeTest.objects(test_id=2).first()
        self.assertEqual(dt2.created_at.isoformat(), datetime(today.year, today.month, today.day).isoformat())

        result = self.DatetimeTest.objects.all().allow_filtering().filter(test_id=2).first()
        self.assertEqual(result.created_at, datetime.combine(today, datetime.min.time()))

        result = self.DatetimeTest.objects.all().allow_filtering().filter(test_id=2, created_at=today).first()
        self.assertEqual(result.created_at, datetime.combine(today, datetime.min.time()))
task.py 文件源码 项目:todoist_scheduler 作者: ViliamV 项目源码 文件源码 阅读 42 收藏 0 点赞 0 评论 0
def execute(task, user, verbose, filename, frontload=0):
    due_date = parse(task['due_date']).date()
    early = string_to_relativedelta(task['early'])
    todoist_project = None
    new_task = task.copy()
    rewrite = False
    interval = string_to_relativedelta(task['interval'])
    while date.today() + relativedelta(days=frontload) >= due_date - early:
        if todoist_project is None:
            todoist_project = user.get_project(task['project'])
        if task['interval'] is None:
            # One time task
            for t in task['tasks']:
                todoist_project.add_task(t, date=task['due_date'], priority=task['priority'])
                if verbose: print('-> Added new task \'{}\' with due date {}.'
                        .format(t, task['due_date']), flush=True)
            delete(task, filename, verbose)
            break
        else:
            # Recurring task
            todoist_project.add_task(new_task['tasks'][new_task['index']],
                                     date=new_task['due_date'], priority=task['priority'])
            if verbose: print('-> Added new task \'{}\' with due date {}.'
                    .format(new_task['tasks'][new_task['index']], new_task['due_date']), flush=True)
            # incrementing values
            if interval.days == -1: # last day of month
                due_date += relativedelta(days=+1)
            due_date += interval
            new_task['due_date'] = due_date.isoformat()
            new_task['index'] = (new_task['index'] + 1) % len(new_task['tasks'])
            rewrite = True
    if rewrite: write(new_task, filename, verbose)
tests.py 文件源码 项目:miniluv 作者: fsantovito 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_timeedit(self):
        dt = time(11, 12, 13)
        self.assertEqual(model.timeedit, None)
        view.ui.timeedit.setTime(dt)
        self.assertEqual(model.timeedit, dt)

        dt = datetime.combine(date.today(), dt) + timedelta(minutes=30)
        dt = dt.time()
        model.timeedit = dt
        self.assertEqual(view.ui.timeedit.time(), model.timeedit)
test_cache_project_stats.py 文件源码 项目:FRG-Crowdsourcing 作者: 97amarnathk 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_stats_users_with_period(self):
        """Test CACHE PROJECT STATS user stats with period works."""
        pr = ProjectFactory.create()
        d = date.today() - timedelta(days=6)
        TaskRunFactory.create(project=pr, created=d, finish_time=d)
        d = date.today() - timedelta(days=16)
        AnonymousTaskRunFactory.create(project=pr, created=d, finish_time=d)
        users, anon_users, auth_users = stats_users(pr.id, '1 week')
        assert len(users) == 2, len(users)
        assert len(anon_users) == 0, len(anon_users)
        assert len(auth_users) == 1, len(auth_users)
test_cache_project_stats.py 文件源码 项目:FRG-Crowdsourcing 作者: 97amarnathk 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_stats_dates(self):
        """Test CACHE PROJECT STATS date works."""
        pr = ProjectFactory.create()
        task = TaskFactory.create(project=pr, n_answers=1)
        today = datetime.now(pytz.utc)
        TaskFactory.create()
        TaskRunFactory.create(project=pr, task=task)
        AnonymousTaskRunFactory.create(project=pr)
        dates, dates_anon, dates_auth = stats_dates(pr.id)
        assert len(dates) == 15, len(dates)
        assert len(dates_anon) == 15, len(dates_anon)
        assert len(dates_auth) == 15, len(dates_auth)
        assert dates[today.strftime('%Y-%m-%d')] == 1
        assert dates_anon[today.strftime('%Y-%m-%d')] == 1
        assert dates_auth[today.strftime('%Y-%m-%d')] == 1
test_cache_project_stats.py 文件源码 项目:FRG-Crowdsourcing 作者: 97amarnathk 项目源码 文件源码 阅读 46 收藏 0 点赞 0 评论 0
def test_stats_dates_with_period(self):
        """Test CACHE PROJECT STATS dates with period works."""
        pr = ProjectFactory.create()
        d = date.today() - timedelta(days=6)
        task = TaskFactory.create(project=pr, n_answers=1, created=d)
        TaskRunFactory.create(project=pr, task=task, created=d, finish_time=d)
        dd = date.today() - timedelta(days=16)
        AnonymousTaskRunFactory.create(project=pr, created=dd, finish_time=dd)
        dates, dates_anon, dates_auth = stats_dates(pr.id, '1 week')
        assert len(dates) == 7, len(dates)
        assert len(dates_anon) == 7, len(dates_anon)
        assert len(dates_auth) == 7, len(dates_auth)
        assert dates[d.strftime('%Y-%m-%d')] == 1
        assert dates_anon[d.strftime('%Y-%m-%d')] == 0
        assert dates_auth[d.strftime('%Y-%m-%d')] == 1
dates.py 文件源码 项目:sndlatr 作者: Schibum 项目源码 文件源码 阅读 28 收藏 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)
utils.py 文件源码 项目:cloudhealth-client 作者: cloudify-cosmo 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def _get_yesterdays_date():
    current = date.today()
    current_time = datetime.utcnow()
    if current.day == 1:
        if current_time.hour <= 5:
            return date(current.year, current.month-1, (calendar.monthrange(current.year, current.month-1)[2])).strftime('%Y-%m-%d')
        else:
            return date(current.year, current.month-1, (calendar.monthrange(current.year, current.month-1)[1])).strftime('%Y-%m-%d')
    else:
        if current_time.hour <= 5:
            return date(current.year, current.month, current.day-2).strftime('%Y-%m-%d')
        else:
            return date(current.year, current.month, current.day-1).strftime('%Y-%m-%d')
utils.py 文件源码 项目:cloudhealth-client 作者: cloudify-cosmo 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def _get_last_month():
    current = date.today()
    if current.day == 31:
        return date(current.year, current.month-1, (calendar.monthrange(current.year, current.month-1)[1])).strftime('%Y-%m')
    else:
        return date(current.year, current.month-1, current.day).strftime('%Y-%m')
wallstreet.py 文件源码 项目:wallstreet 作者: mcdallas 项目源码 文件源码 阅读 44 收藏 0 点赞 0 评论 0
def __init__(self, quote, opt_type, d=date.today().day, m=date.today().month,
                 y=date.today().year, strict=False, source='google'):

        self.source = source.lower()
        self.underlying = Stock(quote, source=self.source)

        if self.source == 'google':
            self._google(quote, d, m, y)

        elif self.source == 'yahoo':
            self._yahoo(quote, d, m, y)

        self._exp = [exp for exp in self._exp if exp not in self._skip_dates[opt_type]]
        self.expirations = [exp.strftime(DATE_FORMAT) for exp in self._exp]
        self.expiration = date(y, m, d)

        try:
            if opt_type == 'Call':
                self.data = self.data['calls']
            elif opt_type == 'Put':
                self.data = self.data['puts']
            assert self.data

        except (KeyError, AssertionError):
            if self._expiration in self._exp:  # Date is in expirations list but no data for it
                self._skip_dates[opt_type].add(self._expiration)
                self._exp.remove(self._expiration)
                self._has_run = False

            if all((d, m, y)) and not self._has_run and not strict:
                closest_date = min(self._exp, key=lambda x: abs(x - self._expiration))
                print('No options listed for given date, using %s instead' % closest_date.strftime(DATE_FORMAT))
                self._has_run = True
                self.__init__(quote, closest_date.day, closest_date.month, closest_date.year, source=source)
            else:
                raise ValueError('Possible expiration dates for this option are:', self.expirations) from None


问题


面经


文章

微信
公众号

扫码关注公众号