本文整理汇总了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
示例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)
示例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:
# 调用新浪接口发现返回的是所有委托,请求时的传递的时间参数没有任何作用
示例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
示例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
示例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
示例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')
示例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)
示例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)
示例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)
示例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
示例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
示例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")
示例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
示例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)