Python datetime.datetime.strftime() Examples
The following are 30
code examples of datetime.datetime.strftime().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
datetime.datetime
, or try the search function
.
Example #1
Source File: mlbgamedata.py From mlbv with GNU General Public License v3.0 | 7 votes |
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
Example #2
Source File: smithsonian.py From cccatalog with MIT License | 6 votes |
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)
Example #3
Source File: image.py From cccatalog with MIT License | 6 votes |
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
Example #4
Source File: standings.py From mlbv with GNU General Public License v3.0 | 6 votes |
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)
Example #5
Source File: sina.py From backtrader-cn with GNU General Public License v3.0 | 6 votes |
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: # 调用新浪接口发现返回的是所有委托,请求时的传递的时间参数没有任何作用
Example #6
Source File: analysismonitor.py From magpy with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #7
Source File: tests.py From BikeMaps with MIT License | 6 votes |
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")
Example #8
Source File: conftest.py From linkedevents with MIT License | 6 votes |
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
Example #9
Source File: utils.py From wagtail-tag-manager with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #10
Source File: standards.py From python_moztelemetry with Mozilla Public License 2.0 | 6 votes |
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)
Example #11
Source File: standards.py From python_moztelemetry with Mozilla Public License 2.0 | 6 votes |
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)
Example #12
Source File: handlers.py From browserscope with Apache License 2.0 | 6 votes |
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
Example #13
Source File: handlers.py From browserscope with Apache License 2.0 | 6 votes |
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
Example #14
Source File: test_gcp_report_processor.py From koku with GNU Affero General Public License v3.0 | 6 votes |
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)
Example #15
Source File: trains.py From iquery with MIT License | 6 votes |
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')
Example #16
Source File: tests.py From BikeMaps with MIT License | 5 votes |
def setUp(self): self.test_user = create_user() self.pnt_geom = '{"type": "Point", "coordinates": [-123, 48]}' self.poly_geom = '{"type": "Polygon", "coordinates": [[[-124,48],[-124,49],[-123,49],[-123,48],[-124,48]]]}' self.now_time = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M")
Example #17
Source File: DateTimeEditDelegateQt.py From KStock with GNU General Public License v3.0 | 5 votes |
def displayText(self, value, locale): ''' Show the date in the specified format. ''' try: if QT_VERSION_STR[0] == '4': date = value.toPyObject() # QVariant ==> datetime elif QT_VERSION_STR[0] == '5': date = value return date.strftime(self.format) except: return ""
Example #18
Source File: base.py From recon-ng with GNU General Public License v3.0 | 5 votes |
def _do_workspaces_list(self, params): '''Lists existing workspaces''' rows = [] for workspace in self._get_workspaces(): db_path = os.path.join(self.spaces_path, workspace, 'data.db') modified = datetime.fromtimestamp(os.path.getmtime(db_path)).strftime('%Y-%m-%d %H:%M:%S') rows.append((workspace, modified)) rows.sort(key=lambda x: x[0]) self.table(rows, header=['Workspaces', 'Modified'])
Example #19
Source File: base.py From recon-ng with GNU General Public License v3.0 | 5 votes |
def do_index(self, params): '''Creates a module index (dev only)''' mod_path, file_name = self._parse_params(params) if not mod_path: self.help_index() return self.output('Building index markup...') yaml_objs = [] modules = [m for m in self._loaded_modules.items() if mod_path in m[0] or mod_path == 'all'] for path, module in sorted(modules, key=lambda k: k[0]): yaml_obj = {} # not in meta yaml_obj['path'] = path yaml_obj['last_updated'] = datetime.strftime(datetime.now(), '%Y-%m-%d') # meta required yaml_obj['author'] = module.meta.get('author') yaml_obj['name'] = module.meta.get('name') yaml_obj['description'] = module.meta.get('description') yaml_obj['version'] = module.meta.get('version', '1.0') # meta optional #yaml_obj['comments'] = module.meta.get('comments', []) yaml_obj['dependencies'] = module.meta.get('dependencies', []) yaml_obj['files'] = module.meta.get('files', []) #yaml_obj['options'] = module.meta.get('options', []) #yaml_obj['query'] = module.meta.get('query', '') yaml_obj['required_keys'] = module.meta.get('required_keys', []) yaml_objs.append(yaml_obj) if yaml_objs: markup = yaml.safe_dump(yaml_objs) print(markup) # write to file if index name provided if file_name: with open(file_name, 'w') as outfile: outfile.write(markup) self.output('Module index created.') else: self.output('No modules found.')
Example #20
Source File: test_db.py From odoorpc with GNU Lesser General Public License v3.0 | 5 votes |
def test_db_create(self): date = datetime.strftime(datetime.today(), '%Y%m%d_%Hh%Mm%S') new_database = "%s_%s" % (self.env['db'], date) self.databases.append(new_database) self.odoo.db.create(self.env['super_pwd'], new_database)
Example #21
Source File: DateTimeEditDelegateQt.py From KStock with GNU General Public License v3.0 | 5 votes |
def createEditor(self, parent, option, index): ''' Return a QLineEdit for arbitrary representation of a date value in any format. ''' editor = QLineEdit(parent) date = index.model().data(index, Qt.DisplayRole) editor.setText(date.strftime(self.format)) return editor
Example #22
Source File: config.py From LiMEaide with GNU General Public License v3.0 | 5 votes |
def set_date(self): self.date = datetime.strftime(datetime.today(), "%Y_%m_%dT%H_%M_%S")
Example #23
Source File: test_db.py From odoorpc with GNU Lesser General Public License v3.0 | 5 votes |
def test_db_create_wrong_password(self): date = datetime.strftime(datetime.today(), '%Y%m%d_%Hh%Mm%S') new_database = "%s_%s" % (self.env['db'], date) self.databases.append(new_database) self.assertRaises( odoorpc.error.RPCError, self.odoo.db.create, 'wrong_password', new_database)
Example #24
Source File: gcp_report_processor.py From koku with GNU Affero General Public License v3.0 | 5 votes |
def _get_or_create_cost_entry_bill(self, row, report_db_accessor): """Get or Create a GCP cost entry bill object. Args: row (OrderedDict): A dictionary representation of a CSV file row. Returns: (string) An id of a GCP Bill. """ table_name = GCPCostEntryBill start_time = row["Start Time"] 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) data = { "billing_period_start": datetime.strftime(start_date_utc, "%Y-%m-%d %H:%M%z"), "billing_period_end": datetime.strftime(end_date_utc, "%Y-%m-%d %H:%M%z"), "provider_id": self._provider_uuid, } key = (start_date_utc, self._provider_uuid) if key in self.processed_report.bills: return self.processed_report.bills[key] bill_id = report_db_accessor.insert_on_conflict_do_nothing( table_name, data, conflict_columns=["billing_period_start", "provider_id"] ) self.processed_report.bills[key] = bill_id return bill_id
Example #25
Source File: azure_report_processor.py From koku with GNU Affero General Public License v3.0 | 5 votes |
def _create_cost_entry_bill(self, row, report_db_accessor): """Create a cost entry bill object. Args: row (dict): A dictionary representation of a CSV file row Returns: (str): A cost entry bill object id """ table_name = AzureCostEntryBill row_date = row.get("UsageDateTime") report_date_range = utils.month_date_range(parser.parse(row_date)) 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) key = (start_date_utc, self._provider_uuid) if key in self.processed_report.bills: return self.processed_report.bills[key] if key in self.existing_bill_map: return self.existing_bill_map[key] data = self._get_data_for_table(row, table_name._meta.db_table) data["provider_id"] = self._provider_uuid data["billing_period_start"] = datetime.strftime(start_date_utc, "%Y-%m-%d %H:%M%z") data["billing_period_end"] = datetime.strftime(end_date_utc, "%Y-%m-%d %H:%M%z") bill_id = report_db_accessor.insert_on_conflict_do_nothing( table_name, data, conflict_columns=["billing_period_start", "provider_id"] ) self.processed_report.bills[key] = bill_id return bill_id
Example #26
Source File: mlbgamedata.py From mlbv with GNU General Public License v3.0 | 5 votes |
def process_game_data(self, game_date, num_days=1): game_days_list = list() for i in range(0, num_days): game_records = self._get_games_by_date(game_date) if game_records is not None: game_days_list.append((game_date, game_records)) game_date = datetime.strftime(datetime.strptime(game_date, "%Y-%m-%d") + timedelta(days=1), "%Y-%m-%d") return game_days_list
Example #27
Source File: showes.py From iquery with MIT License | 5 votes |
def date_range(self): """Generate date range according to the `days` user input.""" try: days = int(self.days) except ValueError: exit_after_echo(QUERY_DAYS_INVALID) if days < 1: exit_after_echo(QUERY_DAYS_INVALID) start = datetime.today() end = start + timedelta(days=days) return ( datetime.strftime(start, '%Y-%m-%d'), datetime.strftime(end, '%Y-%m-%d') )
Example #28
Source File: models.py From longclaw with MIT License | 5 votes |
def refund(self): """Issue a full refund for this order """ from longclaw.utils import GATEWAY now = datetime.strftime(datetime.now(), "%b %d %Y %H:%M:%S") if GATEWAY.issue_refund(self.transaction_id, self.total): self.status = self.REFUNDED self.status_note = "Refunded on {}".format(now) else: self.status_note = "Refund failed on {}".format(now) self.save()
Example #29
Source File: test_db.py From odoorpc with GNU Lesser General Public License v3.0 | 5 votes |
def test_db_drop(self): date = datetime.strftime(datetime.today(), '%Y%m%d_%Hh%Mm%S') new_database = "%s_%s" % (self.env['db'], date) self.databases.append(new_database) self.odoo.db.duplicate( self.env['super_pwd'], self.env['db'], new_database) res = self.odoo.db.drop(self.env['super_pwd'], new_database) self.assertTrue(res)
Example #30
Source File: client_test.py From galaxy-fds-sdk-python with Apache License 2.0 | 5 votes |
def setUpClass(cls): ClientTest.init_from_local_config() config = FDSClientConfiguration( region_name=region_name, enable_https=False, enable_cdn_for_upload=False, enable_cdn_for_download=False, endpoint=endpoint) config.enable_md5_calculate = True ClientTest.client = GalaxyFDSClient(access_key, access_secret, config) ClientTest.bucket_name = 'test-python-' + datetime.strftime(datetime.now(), "%Y%m%d%H%M%S%z") ClientTest.delete_objects_and_bucket(cls.client, cls.bucket_name) ClientTest.client.create_bucket(cls.bucket_name)