當前位置: 首頁>>代碼示例>>Python>>正文


Python datetime.strftime方法代碼示例

本文整理匯總了Python中datetime.datetime.strftime方法的典型用法代碼示例。如果您正苦於以下問題:Python datetime.strftime方法的具體用法?Python datetime.strftime怎麽用?Python datetime.strftime使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在datetime.datetime的用法示例。


在下文中一共展示了datetime.strftime方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _get_header

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strftime [as 別名]
def _get_header(border, game_date, show_scores, show_linescore):
        header = list()
        date_hdr = '{:7}{} {}'.format('', game_date, datetime.strftime(datetime.strptime(game_date, "%Y-%m-%d"), "%a"))
        if show_scores:
            if show_linescore:
                header.append("{:56}".format(date_hdr))
                header.append('{c_on}{dash}{c_off}'
                              .format(c_on=border.border_color, dash=border.thickdash*92, c_off=border.color_off))
            else:
                header.append("{:48} {:^7} {pipe} {:^5} {pipe} {:^9} {pipe} {}"
                              .format(date_hdr, 'Series', 'Score', 'State', 'Feeds', pipe=border.pipe))
                header.append("{c_on}{}{pipe}{}{pipe}{}{pipe}{}{c_off}"
                              .format(border.thickdash * 57, border.thickdash * 7, border.thickdash * 11, border.thickdash * 16,
                                      pipe=border.junction, c_on=border.border_color, c_off=border.color_off))
        else:
            header.append("{:48} {:^7} {pipe} {:^9} {pipe} {}".format(date_hdr, 'Series', 'State', 'Feeds', pipe=border.pipe))
            header.append("{c_on}{}{pipe}{}{pipe}{}{c_off}"
                          .format(border.thickdash * 57, border.thickdash * 11, border.thickdash * 16,
                                  pipe=border.junction, c_on=border.border_color, c_off=border.color_off))
        return header 
開發者ID:kmac,項目名稱:mlbv,代碼行數:22,代碼來源:mlbgamedata.py

示例2: get_standings

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strftime [as 別名]
def get_standings(standings_option='all', date_str=None, args_filter=None):
    """Displays standings."""
    LOG.debug('Getting standings for %s, option=%s', date_str, standings_option)
    if date_str == time.strftime("%Y-%m-%d"):
        # strip out date string from url (issue #5)
        date_str = None
    if util.substring_match(standings_option, 'all') or util.substring_match(standings_option, 'division'):
        display_division_standings(date_str, args_filter, rank_tag='divisionRank', header_tags=('league', 'division'))
        if util.substring_match(standings_option, 'all'):
            print('')
    if util.substring_match(standings_option, 'all') or util.substring_match(standings_option, 'wildcard'):
        _display_standings('wildCard', 'Wildcard', date_str, args_filter, rank_tag='wildCardRank', header_tags=('league', ))
        if util.substring_match(standings_option, 'all'):
            print('')
    if util.substring_match(standings_option, 'all') or util.substring_match(standings_option, 'overall') \
            or util.substring_match(standings_option, 'league') or util.substring_match(standings_option, 'conference'):
        _display_standings('byLeague', 'League', date_str, args_filter, rank_tag='leagueRank', header_tags=('league', ))
        if util.substring_match(standings_option, 'all'):
            print('')

    if util.substring_match(standings_option, 'playoff') or util.substring_match(standings_option, 'postseason'):
        _display_standings('postseason', 'Playoffs', date_str, args_filter)
    if util.substring_match(standings_option, 'preseason'):
        _display_standings('preseason', 'Preseason', date_str, args_filter) 
開發者ID:kmac,項目名稱:mlbv,代碼行數:26,代碼來源:standings.py

示例3: _query_orders

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strftime [as 別名]
def _query_orders(self, from_position=0, per_page=10):
        """
        查詢當日委托
        :param from_position: 從第幾個開始
        :param per_page: 每頁返回個數
        :return:
        """
        url = "http://jiaoyi.sina.com.cn/api/jsonp_v2.php/jsonp_%s_%s/V2_CN_Order_Service.getOrder" % (
            get_unix_timestamp(), get_random_string())
        r = self.session.get(
            url, params={
                "sid": self.uid,
                "cid": 10000,
                "sdate": datetime.strftime(datetime.now(), '%Y-%m-%d'),
                "edate": "",
                "from": from_position,  # 請求偏移0
                "count": per_page,  # 每個返回個數
                "sort": 1
            })
        return jsonp2dict(r.text)

    # fixme:
    # 調用新浪接口發現返回的是所有委托,請求時的傳遞的時間參數沒有任何作用 
開發者ID:pandalibin,項目名稱:backtrader-cn,代碼行數:25,代碼來源:sina.py

示例4: Expires

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strftime [as 別名]
def Expires(request):
  """Cookie Expires Test (1 of 2)"""

  params = {
    'page_title': 'Cookie Expires Test',
  }
  response = util.Render(request, 'templates/tests/expires.html', params, 
                         CATEGORY)
  
  expiresInPast = datetime.strftime(datetime.utcnow() + timedelta(hours=-5), 
                                    "%a, %d-%b-%Y %H:%M:%S GMT")
  expiresInFuture = datetime.strftime(datetime.utcnow() + timedelta(hours=5), 
                                      "%a, %d-%b-%Y %H:%M:%S GMT")
  
  # test one each of: cookie with past expires date, session cookie, cookie 
  # with future expires date
  response.set_cookie(EXPIRESCOOKIE1, value="Cookie", expires=expiresInPast)
  response.set_cookie(EXPIRESCOOKIE2, value="Cookie", expires=None)
  response.set_cookie(EXPIRESCOOKIE3, value="Cookie", expires=expiresInFuture)
  return response 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:22,代碼來源:handlers.py

示例5: Expires2

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strftime [as 別名]
def Expires2(request):
  """Cookie Expires Test (2 of 2)"""

  # number 1 should have been deleted, numbers 2 and 3 shouldn't have been
  if None == request.COOKIES.get(EXPIRESCOOKIE1) \
    and not None == request.COOKIES.get(EXPIRESCOOKIE2) \
    and not None == request.COOKIES.get(EXPIRESCOOKIE3):
    
    cookie_deleted = 1
  else:
    cookie_deleted = 0

  params = {
    'page_title': 'Cookie Expires Test',
    'cookie_deleted': cookie_deleted,
  }
  response = util.Render(request, 'templates/tests/expires2.html', params, 
                         CATEGORY)
  # now delete number 2 to clear the way for future tests
  expires = datetime.strftime(datetime.utcnow() + timedelta(hours=-1), 
                              "%a, %d-%b-%Y %H:%M:%S GMT")
  response.set_cookie(EXPIRESCOOKIE2, value="", expires=expires)
  return response 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:25,代碼來源:handlers.py

示例6: _writelog

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strftime [as 別名]
def _writelog(self, loglist, path, timerange=10):
        print("Saving new logfile to {}".format(path))
        #try:
        # Last line summary
        changelist = [[line.split(' : ')[0],line.split(' : ')[-2]] for line in loglist if len(line) > 0 and not line.startswith('KEY') and not line.startswith('SUMMARY')]
        testtime = datetime.utcnow()-timedelta(minutes=timerange)
        N = [el[0] for el in changelist if datetime.strptime(el[1],"%Y-%m-%dT%H:%M:%S")>testtime]
        lastline = "SUMMARY: {} key(s) changed its/their status since {}:  {}".format(len(N),datetime.strftime(testtime,"%Y-%m-%d %H:%M:%S"),N)
        #print ("LOGLIST looks like:", loglist)
        loglist = [line for line in loglist if not line.startswith('SUMMARY')]
        loglist.append(lastline)
        #print ("LOGLIST looks like:", loglist)
        f = io.open(path,'wt', newline='', encoding='utf-8')
        for log in loglist:
            f.write(log+'\r\n')
        f.close()
        print ("... success")
        return True
        #except:
        #    print ("... failure")
        #    return False 
開發者ID:geomagpy,項目名稱:magpy,代碼行數:23,代碼來源:analysismonitor.py

示例7: _valid_date

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strftime [as 別名]
def _valid_date(self):
        """Check and return a valid query date."""
        date = self._parse_date(self.date)

        if not date:
            exit_after_echo(INVALID_DATE)

        try:
            date = datetime.strptime(date, '%Y%m%d')
        except ValueError:
            exit_after_echo(INVALID_DATE)

        # A valid query date should within 50 days.
        offset = date - datetime.today()
        if offset.days not in range(-1, 50):
            exit_after_echo(INVALID_DATE)

        return datetime.strftime(date, '%Y-%m-%d') 
開發者ID:protream,項目名稱:iquery,代碼行數:20,代碼來源:trains.py

示例8: test_get_gcp_cost_entry_bill

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strftime [as 別名]
def test_get_gcp_cost_entry_bill(self):
        """Test calling _get_or_create_cost_entry_bill on an entry bill that exists fetches its id."""
        start_time = "2019-09-17T00:00:00-07:00"
        report_date_range = utils.month_date_range(parser.parse(start_time))
        start_date, end_date = report_date_range.split("-")

        start_date_utc = parser.parse(start_date).replace(hour=0, minute=0, tzinfo=pytz.UTC)
        end_date_utc = parser.parse(end_date).replace(hour=0, minute=0, tzinfo=pytz.UTC)

        with schema_context(self.schema):
            entry_bill = GCPCostEntryBill.objects.create(
                provider=self.gcp_provider, billing_period_start=start_date_utc, billing_period_end=end_date_utc
            )
        entry_bill_id = self.processor._get_or_create_cost_entry_bill(
            {"Start Time": datetime.strftime(start_date_utc, "%Y-%m-%d %H:%M%z")}, self.accessor
        )
        self.assertEquals(entry_bill.id, entry_bill_id) 
開發者ID:project-koku,項目名稱:koku,代碼行數:19,代碼來源:test_gcp_report_processor.py

示例9: dau

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strftime [as 別名]
def dau(dataframe, target_day, future_days=10, date_format="%Y%m%d"):
    """Compute Daily Active Users (DAU) from the Executive Summary dataset.
    See https://bugzilla.mozilla.org/show_bug.cgi?id=1240849
    """
    target_day_date = datetime.strptime(target_day, date_format)
    min_activity = unix_time_nanos(target_day_date)
    max_activity = unix_time_nanos(target_day_date + timedelta(1))
    act_col = dataframe.activityTimestamp

    min_submission = target_day
    max_submission_date = target_day_date + timedelta(future_days)
    max_submission = datetime.strftime(max_submission_date, date_format)
    sub_col = dataframe.submission_date_s3

    filtered = filter_date_range(dataframe, act_col, min_activity, max_activity,
                                 sub_col, min_submission, max_submission)
    return count_distinct_clientids(filtered) 
開發者ID:mozilla,項目名稱:python_moztelemetry,代碼行數:19,代碼來源:standards.py

示例10: mau

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strftime [as 別名]
def mau(dataframe, target_day, past_days=28, future_days=10, date_format="%Y%m%d"):
    """Compute Monthly Active Users (MAU) from the Executive Summary dataset.
    See https://bugzilla.mozilla.org/show_bug.cgi?id=1240849
    """
    target_day_date = datetime.strptime(target_day, date_format)

    # Compute activity over `past_days` days leading up to target_day
    min_activity_date = target_day_date - timedelta(past_days)
    min_activity = unix_time_nanos(min_activity_date)
    max_activity = unix_time_nanos(target_day_date + timedelta(1))
    act_col = dataframe.activityTimestamp

    min_submission = datetime.strftime(min_activity_date, date_format)
    max_submission_date = target_day_date + timedelta(future_days)
    max_submission = datetime.strftime(max_submission_date, date_format)
    sub_col = dataframe.submission_date_s3

    filtered = filter_date_range(dataframe, act_col, min_activity, max_activity,
                                 sub_col, min_submission, max_submission)
    return count_distinct_clientids(filtered) 
開發者ID:mozilla,項目名稱:python_moztelemetry,代碼行數:22,代碼來源:standards.py

示例11: set_cookie

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strftime [as 別名]
def set_cookie(response, key, value, days_expire=None):
    if days_expire is None:
        expires = getattr(settings, "WTM_COOKIE_EXPIRE", 365)
        max_age = expires * 24 * 60 * 60  # one year
    else:
        max_age = days_expire * 24 * 60 * 60

    delta = datetime.utcnow() + timedelta(seconds=max_age)
    expires = datetime.strftime(delta, "%a, %d-%b-%Y %H:%M:%S GMT")

    kwargs = {
        "max_age": max_age,
        "expires": expires,
        "domain": getattr(settings, "SESSION_COOKIE_DOMAIN"),
        "secure": getattr(settings, "SESSION_COOKIE_SECURE", None),
        "httponly": False,
    }

    if not __version__.startswith("2.0"):
        kwargs["samesite"] = "Lax"

    response.set_cookie(key, value, **kwargs)
    patch_vary_headers(response, ("Cookie",))

    return response 
開發者ID:jberghoef,項目名稱:wagtail-tag-manager,代碼行數:27,代碼來源:utils.py

示例12: make_minimal_event_dict

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strftime [as 別名]
def make_minimal_event_dict(make_keyword_id):
    def _make_minimal_event_dict(data_source, organization, location_id):
        return {
            'name': {'fi': TEXT_FI},
            'start_time': datetime.strftime(timezone.now() + timedelta(days=1), '%Y-%m-%d'),
            'location': {'@id': location_id},
            'keywords': [
                {'@id': make_keyword_id(data_source, 'test')},
            ],
            'short_description': {'fi': 'short desc', 'sv': 'short desc sv', 'en': 'short desc en'},
            'description': {'fi': 'desc', 'sv': 'desc sv', 'en': 'desc en'},
            'offers': [
                {
                    'is_free': False,
                    'price': {'en': TEXT_EN, 'sv': TEXT_SV, 'fi': TEXT_FI},
                    'description': {'en': TEXT_EN, 'sv': TEXT_SV, 'fi': TEXT_FI},
                    'info_url': {'en': URL, 'sv': URL, 'fi': URL}
                }
            ],
            'publisher': organization.id
        }

    return _make_minimal_event_dict 
開發者ID:City-of-Helsinki,項目名稱:linkedevents,代碼行數:25,代碼來源:conftest.py

示例13: setUp

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strftime [as 別名]
def setUp(self):
        test_user = create_user()

        poly_geom = GEOSGeometry('POLYGON((-124 48, -124 49, -123 49, -123 48, -124 48))')
        pnt_in_poly_geom = GEOSGeometry('POINT(-123.5 48.5)')
        pnt_out_poly_geom = GEOSGeometry('POINT(-122 48)')

        now = datetime.now()
        now_time = datetime.strftime(now, "%Y-%m-%d %H:%M")
        week_ago_time = datetime.strftime(now - timedelta(weeks=1), "%Y-%m-%d %H:%M")

        self._poly = AlertArea.objects.create(geom=poly_geom, user=test_user)

        # Create points inside the alert area
        self._pnt_in_poly = Incident.objects.create(geom=pnt_in_poly_geom, date=now_time,
                                                    i_type="Collision with moving object or vehicle",
                                                    incident_with="Vehicle, side",
                                                    injury="Injury, no treatment")
        # Create points outside of alert area
        self._pnt_out_poly = Incident.objects.create(geom=pnt_out_poly_geom, date=week_ago_time,
                                                     i_type="Near collision with stationary object or vehicle",
                                                     incident_with="Vehicle, side",
                                                     injury="Injury, no treatment") 
開發者ID:SPARLab,項目名稱:BikeMaps,代碼行數:25,代碼來源:tests.py

示例14: _initialize_output_path

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strftime [as 別名]
def _initialize_output_path(self, output_dir, output_file, provider):
        if output_dir is None:
            logger.info(
                'No given output directory.  '
                'Using OUTPUT_DIR from environment.'
            )
            output_dir = os.getenv('OUTPUT_DIR')
        if output_dir is None:
            logger.warning(
                'OUTPUT_DIR is not set in the enivronment.  '
                'Output will go to /tmp.'
            )
            output_dir = '/tmp'

        if output_file is not None:
            output_file = str(output_file)
        else:
            output_file = '{}_{}.tsv'.format(
                provider, datetime.strftime(self._NOW, '%Y%m%d%H%M%S')
            )

        output_path = os.path.join(output_dir, output_file)
        logger.info('Output path: {}'.format(output_path))
        return output_path 
開發者ID:creativecommons,項目名稱:cccatalog,代碼行數:26,代碼來源:image.py

示例15: gather_samples

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strftime [as 別名]
def gather_samples(
        units_endpoint=UNITS_ENDPOINT,
        default_params=DEFAULT_PARAMS,
        target_dir='/tmp'
):
    """
    Gather random samples of the rows from each 'unit' at the SI.

    These units are treated separately since they have somewhat
    different data formats.

    This function is for gathering test data only, and is untested.
    """
    now_str = datetime.strftime(datetime.now(), '%Y%m%d%H%M%S')
    sample_dir = os.path.join(target_dir, f'si_samples_{now_str}')
    logger.info(f'Creating sample_dir {sample_dir}')
    os.mkdir(sample_dir)
    unit_code_json = delayed_requester.get_response_json(
        units_endpoint,
        query_params=default_params
    )
    unit_code_list = unit_code_json.get('response', {}).get('terms', [])
    logger.info(f'found unit codes: {unit_code_list}')
    for unit in unit_code_list:
        _gather_unit_sample(unit, sample_dir) 
開發者ID:creativecommons,項目名稱:cccatalog,代碼行數:27,代碼來源:smithsonian.py


注:本文中的datetime.datetime.strftime方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。