Python datetime.datetime.today() Examples
The following are 30
code examples of datetime.datetime.today().
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: utils.py From ffplayout-engine with GNU General Public License v3.0 | 7 votes |
def get_time(time_format): """ get different time formats: - full_sec > current time in seconds - stamp > current date time in seconds - else > current time in HH:MM:SS """ t = datetime.today() if time_format == 'full_sec': return t.hour * 3600 + t.minute * 60 + t.second \ + t.microsecond / 1000000 elif time_format == 'stamp': return float(datetime.now().timestamp()) else: return t.strftime('%H:%M:%S') # ------------------------------------------------------------------------------ # default variables and values # ------------------------------------------------------------------------------
Example #2
Source File: test_tools.py From recruit with Apache License 2.0 | 6 votes |
def test_datetime_bool(self, cache): # GH13176 with pytest.raises(TypeError): to_datetime(False) assert to_datetime(False, errors="coerce", cache=cache) is NaT assert to_datetime(False, errors="ignore", cache=cache) is False with pytest.raises(TypeError): to_datetime(True) assert to_datetime(True, errors="coerce", cache=cache) is NaT assert to_datetime(True, errors="ignore", cache=cache) is True with pytest.raises(TypeError): to_datetime([False, datetime.today()], cache=cache) with pytest.raises(TypeError): to_datetime(['20130101', True], cache=cache) tm.assert_index_equal(to_datetime([0, False, NaT, 0.0], errors="coerce", cache=cache), DatetimeIndex([to_datetime(0, cache=cache), NaT, NaT, to_datetime(0, cache=cache)]))
Example #3
Source File: sites.py From daimaduan.com with BSD 3-Clause "New" or "Revised" License | 6 votes |
def index(): page = get_page() pagination = Paste.objects(is_private=False).order_by('-updated_at').paginate(page=page, per_page=20) print datetime.today() return render_template('index.html', pagination=pagination, hot_pastes=Paste.objects(is_private=False).order_by('-views')[:10], pastes_count=Paste.objects().count(), comments_count=Comment.objects().count(), users_count=User.objects().count(), syntax_count=Syntax.objects().count(), bookmarks_count=Bookmark.objects().count(), users_increased=User.objects(created_at__gt=date.today()).count(), pastes_increased=Paste.objects(created_at__gt=date.today()).count(), comments_increased=Comment.objects(created_at__gt=date.today()).count(), bookmarks_increased=Bookmark.objects(created_at__gt=date.today()).count(), tags=Tag.objects().order_by('-popularity')[:10])
Example #4
Source File: ProxyTool.py From ProxHTTPSProxyMII with MIT License | 6 votes |
def sendout_error(self, url, code, message=None, explain=None): "Modified from http.server.send_error() for customized display" try: shortmsg, longmsg = self.responses[code] except KeyError: shortmsg, longmsg = '???', '???' if message is None: message = shortmsg if explain is None: explain = longmsg content = (message_format % {'code': code, 'message': message, 'explain': explain, 'url': url, 'now': datetime.today(), 'server': self.server_version}) body = content.encode('UTF-8', 'replace') self.send_response_only(code, message) self.send_header("Content-Type", self.error_content_type) self.send_header('Content-Length', int(len(body))) self.end_headers() if self.command != 'HEAD' and code >= 200 and code not in (204, 304): self.wfile.write(body)
Example #5
Source File: external_api_2_3_tests.py From seqr with GNU Affero General Public License v3.0 | 6 votes |
def test_mme_metrics_proxy(self): url = '/api/matchmaker/v1/metrics' self._check_mme_authenticated(url) response = self._make_mme_request(url, 'get') self.assertEqual(response.status_code, 200) self.assertDictEqual(response.json(), { 'metrics': { 'numberOfCases': 3, 'numberOfSubmitters': 2, 'numberOfUniqueGenes': 4, 'numberOfUniqueFeatures': 4, 'numberOfRequestsReceived': 3, 'numberOfPotentialMatchesSent': 1, 'dateGenerated': datetime.today().strftime('%Y-%m-%d'), } })
Example #6
Source File: test_date_range.py From recruit with Apache License 2.0 | 6 votes |
def test_date_range_normalize(self): snap = datetime.today() n = 50 rng = date_range(snap, periods=n, normalize=False, freq='2D') offset = timedelta(2) values = DatetimeIndex([snap + i * offset for i in range(n)]) tm.assert_index_equal(rng, values) rng = date_range('1/1/2000 08:15', periods=n, normalize=False, freq='B') the_time = time(8, 15) for val in rng: assert val.time() == the_time
Example #7
Source File: abichecker-dbcli.py From openSUSE-release-tools with GNU General Public License v2.0 | 6 votes |
def do_prune(self, subcmd, opts, days): """${cmd_name}: prune old records ${cmd_usage} ${cmd_option_list} """ oldest = datetime.today() - timedelta(days = 365) requests = self.session.query(DB.Request).filter(DB.Request.t_updated < oldest) for req in requests: for a in req.abichecks: self.logger.info('prune %s %s %s', req.id, a.dst_project, a.dst_package) for r in a.reports: fn = os.path.join(CACHEDIR, r.htmlreport) if os.path.exists(fn): self.logger.info('removing %s', r.htmlreport) os.unlink(fn) self.session.delete(req) self.session.commit()
Example #8
Source File: trains.py From iquery with MIT License | 6 votes |
def _parse_date(date): """Parse from the user input `date`. e.g. current year 2016: input 6-26, 626, ... return 2016626 input 2016-6-26, 2016/6/26, ... retrun 2016626 This fn wouldn't check the date, it only gather the number as a string. """ result = ''.join(re.findall('\d', date)) l = len(result) # User only input month and day, eg 6-1, 6.26, 0626... if l in (2, 3, 4): year = str(datetime.today().year) return year + result # User input full format date, eg 201661, 2016-6-26, 20160626... if l in (6, 7, 8): return result return ''
Example #9
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 #10
Source File: test_strings.py From recruit with Apache License 2.0 | 6 votes |
def test_title(self): values = Series(["FOO", "BAR", NA, "Blah", "blurg"]) result = values.str.title() exp = Series(["Foo", "Bar", NA, "Blah", "Blurg"]) tm.assert_series_equal(result, exp) # mixed mixed = Series(["FOO", NA, "bar", True, datetime.today(), "blah", None, 1, 2.]) mixed = mixed.str.title() exp = Series(["Foo", NA, "Bar", NA, NA, "Blah", NA, NA, NA]) tm.assert_almost_equal(mixed, exp) # unicode values = Series([u("FOO"), NA, u("bar"), u("Blurg")]) results = values.str.title() exp = Series([u("Foo"), NA, u("Bar"), u("Blurg")]) tm.assert_series_equal(results, exp)
Example #11
Source File: test_strings.py From recruit with Apache License 2.0 | 6 votes |
def test_capitalize(self): values = Series(["FOO", "BAR", NA, "Blah", "blurg"]) result = values.str.capitalize() exp = Series(["Foo", "Bar", NA, "Blah", "Blurg"]) tm.assert_series_equal(result, exp) # mixed mixed = Series(["FOO", NA, "bar", True, datetime.today(), "blah", None, 1, 2.]) mixed = mixed.str.capitalize() exp = Series(["Foo", NA, "Bar", NA, NA, "Blah", NA, NA, NA]) tm.assert_almost_equal(mixed, exp) # unicode values = Series([u("FOO"), NA, u("bar"), u("Blurg")]) results = values.str.capitalize() exp = Series([u("Foo"), NA, u("Bar"), u("Blurg")]) tm.assert_series_equal(results, exp)
Example #12
Source File: test_strings.py From recruit with Apache License 2.0 | 6 votes |
def test_len(self): values = Series(['foo', 'fooo', 'fooooo', np.nan, 'fooooooo']) result = values.str.len() exp = values.map(lambda x: len(x) if notna(x) else NA) tm.assert_series_equal(result, exp) # mixed mixed = Series(['a_b', NA, 'asdf_cas_asdf', True, datetime.today(), 'foo', None, 1, 2.]) rs = Series(mixed).str.len() xp = Series([3, NA, 13, NA, NA, 3, NA, NA, NA]) assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) # unicode values = Series([u('foo'), u('fooo'), u('fooooo'), np.nan, u( 'fooooooo')]) result = values.str.len() exp = values.map(lambda x: len(x) if notna(x) else NA) tm.assert_series_equal(result, exp)
Example #13
Source File: test_strings.py From recruit with Apache License 2.0 | 6 votes |
def test_findall(self): values = Series(['fooBAD__barBAD', NA, 'foo', 'BAD']) result = values.str.findall('BAD[_]*') exp = Series([['BAD__', 'BAD'], NA, [], ['BAD']]) tm.assert_almost_equal(result, exp) # mixed mixed = Series(['fooBAD__barBAD', NA, 'foo', True, datetime.today(), 'BAD', None, 1, 2.]) rs = Series(mixed).str.findall('BAD[_]*') xp = Series([['BAD__', 'BAD'], NA, [], NA, NA, ['BAD'], NA, NA, NA]) assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) # unicode values = Series([u('fooBAD__barBAD'), NA, u('foo'), u('BAD')]) result = values.str.findall('BAD[_]*') exp = Series([[u('BAD__'), u('BAD')], NA, [], [u('BAD')]]) tm.assert_almost_equal(result, exp)
Example #14
Source File: Dataset.py From dipper with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _set_version_level_triples(self): self.model.addType(self.version_level_curie, self.globaltt['Dataset']) self.graph.addTriple(self.version_level_curie, self.globaltt['title'], self.ingest_title + " Monarch version " + self.data_release_version, True) if self.ingest_description is not None: self.model.addDescription(self.version_level_curie, self.ingest_description) self.graph.addTriple(self.version_level_curie, self.globaltt['Date Created'], Literal(datetime.today().strftime("%Y%m%d"), datatype=XSD.date)) self.graph.addTriple(self.version_level_curie, self.globaltt['version'], Literal(self.data_release_version, datatype=XSD.date)) self.graph.addTriple(self.version_level_curie, self.globaltt['creator'], self.curie_map.get("")) # eval's to MI.org self.graph.addTriple(self.version_level_curie, self.globaltt['Publisher'], self.curie_map.get("")) # eval's to MI.org self.graph.addTriple(self.version_level_curie, self.globaltt['isVersionOf'], self.summary_level_curie, object_is_literal=False) self.graph.addTriple(self.version_level_curie, self.globaltt['distribution'], self.distribution_level_turtle_curie, object_is_literal=False)
Example #15
Source File: test_strings.py From recruit with Apache License 2.0 | 6 votes |
def test_strip_lstrip_rstrip_mixed(self): # mixed mixed = Series([' aa ', NA, ' bb \t\n', True, datetime.today(), None, 1, 2.]) rs = Series(mixed).str.strip() xp = Series(['aa', NA, 'bb', NA, NA, NA, NA, NA]) assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) rs = Series(mixed).str.lstrip() xp = Series(['aa ', NA, 'bb \t\n', NA, NA, NA, NA, NA]) assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp) rs = Series(mixed).str.rstrip() xp = Series([' aa', NA, ' bb', NA, NA, NA, NA, NA]) assert isinstance(rs, Series) tm.assert_almost_equal(rs, xp)
Example #16
Source File: test_timestamp.py From recruit with Apache License 2.0 | 6 votes |
def test_class_ops_dateutil(self): def compare(x, y): assert (int(np.round(Timestamp(x).value / 1e9)) == int(np.round(Timestamp(y).value / 1e9))) compare(Timestamp.now(), datetime.now()) compare(Timestamp.now('UTC'), datetime.now(tzutc())) compare(Timestamp.utcnow(), datetime.utcnow()) compare(Timestamp.today(), datetime.today()) current_time = calendar.timegm(datetime.now().utctimetuple()) compare(Timestamp.utcfromtimestamp(current_time), datetime.utcfromtimestamp(current_time)) compare(Timestamp.fromtimestamp(current_time), datetime.fromtimestamp(current_time)) date_component = datetime.utcnow() time_component = (date_component + timedelta(minutes=10)).time() compare(Timestamp.combine(date_component, time_component), datetime.combine(date_component, time_component))
Example #17
Source File: test_timestamp.py From recruit with Apache License 2.0 | 6 votes |
def test_today(self): ts_from_string = Timestamp('today') ts_from_method = Timestamp.today() ts_datetime = datetime.today() ts_from_string_tz = Timestamp('today', tz='US/Eastern') ts_from_method_tz = Timestamp.today(tz='US/Eastern') # Check that the delta between the times is less than 1s (arbitrarily # small) delta = Timedelta(seconds=1) assert abs(ts_from_method - ts_from_string) < delta assert abs(ts_datetime - ts_from_method) < delta assert abs(ts_from_method_tz - ts_from_string_tz) < delta assert (abs(ts_from_string_tz.tz_localize(None) - ts_from_method_tz.tz_localize(None)) < delta)
Example #18
Source File: example_dv360_sdf_record_advertisers.py From orchestra with Apache License 2.0 | 5 votes |
def yesterday(): return datetime.today() - timedelta(days=1)
Example #19
Source File: countBot.py From IRCBots with MIT License | 5 votes |
def getCurrentTime(): time = match('^(\d+):(\d+)', str(datetime.now().time())) day = datetime.today().weekday() return ("{}:{}:{}".format(time.group(1), time.group(2), day))
Example #20
Source File: TraTicketBooker.py From TRA-Ticket-Booker with GNU General Public License v3.0 | 5 votes |
def get_date_list(self): date_list = [] for ii in range(17): if datetime.today().time().hour < 23: local_time = datetime.today() + timedelta(ii) else: local_time = datetime.today() + timedelta(ii + 1) lt_year, lt_mon, lt_day, lt_hour, lt_min, lt_sec, \ lt_wday, lt_yday, lt_isdst = local_time.timetuple() date_list.append( '%04d/%02d/%02d' % (lt_year, lt_mon, lt_day) ) return date_list
Example #21
Source File: Xiaomi_Scale.py From xiaomi_mi_scale with MIT License | 5 votes |
def handleDiscovery(self, dev, isNewDev, isNewData): global OLD_MEASURE if dev.addr == MISCALE_MAC.lower() and isNewDev: for (sdid, desc, data) in dev.getScanData(): ### Xiaomi V1 Scale ### if data.startswith('1d18') and sdid == 22: measunit = data[4:6] measured = int((data[8:10] + data[6:8]), 16) * 0.01 unit = '' if measunit.startswith(('03', 'b3')): unit = 'lbs' if measunit.startswith(('12', 'b2')): unit = 'jin' if measunit.startswith(('22', 'a2')): unit = 'kg' ; measured = measured / 2 if unit: if OLD_MEASURE != round(measured, 2): self._publish(round(measured, 2), unit, str(datetime.today().strftime('%Y-%m-%d-%H:%M:%S')), "", "") OLD_MEASURE = round(measured, 2) ### Xiaomi V2 Scale ### if data.startswith('1b18') and sdid == 22: data2 = bytes.fromhex(data[4:]) ctrlByte1 = data2[1] isStabilized = ctrlByte1 & (1<<5) hasImpedance = ctrlByte1 & (1<<1) measunit = data[4:6] measured = int((data[28:30] + data[26:28]), 16) * 0.01 unit = '' if measunit == "03": unit = 'lbs' if measunit == "02": unit = 'kg' ; measured = measured / 2 #mitdatetime = datetime.strptime(str(int((data[10:12] + data[8:10]), 16)) + " " + str(int((data[12:14]), 16)) +" "+ str(int((data[14:16]), 16)) +" "+ str(int((data[16:18]), 16)) +" "+ str(int((data[18:20]), 16)) +" "+ str(int((data[20:22]), 16)), "%Y %m %d %H %M %S") miimpedance = str(int((data[24:26] + data[22:24]), 16)) if unit and isStabilized: if OLD_MEASURE != round(measured, 2) + int(miimpedance): self._publish(round(measured, 2), unit, str(datetime.today().strftime('%Y-%m-%d-%H:%M:%S')), hasImpedance, miimpedance) OLD_MEASURE = round(measured, 2) + int(miimpedance)
Example #22
Source File: forms.py From aswan with GNU Lesser General Public License v2.1 | 5 votes |
def clean_end_day(self): end_day = self.cleaned_data.get('end_day', '') if end_day: try: end_day = datetime.strptime(end_day, '%Y/%m/%d') + timedelta( days=1) end_day = end_day.date() except ValueError: end_day = date.today() + timedelta(days=1) else: end_day = date.today() + timedelta(days=1) return end_day
Example #23
Source File: Xiaomi_Scale.py From xiaomi_mi_scale with MIT License | 5 votes |
def GetAge(self, d1): d1 = datetime.strptime(d1, "%Y-%m-%d") d2 = datetime.strptime(datetime.today().strftime('%Y-%m-%d'),'%Y-%m-%d') return abs((d2 - d1).days)/365
Example #24
Source File: test_dataset.py From dipper with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_version_level_created(self): triples = list(self.dataset.graph.triples( (self.version_level_IRI, self.iri_created, None))) self.assertTrue(len(triples) == 1, "didn't get exactly 1 version level created triple") self.assertEqual(triples[0][2], Literal(datetime.today().strftime("%Y%m%d"), datatype=XSD.date), "version level created triple has the wrong timestamp")
Example #25
Source File: Ensembl.py From dipper with BSD 3-Clause "New" or "Revised" License | 5 votes |
def fetch(self, is_dl_forced=True): # it is a database query... so no timestamps for txid in self.tax_ids: LOG.info("Fetching genes for %s", txid) loc_file = '/'.join((self.rawdir, 'ensembl_' + txid + '.txt')) # todo move into util? params = urllib.parse.urlencode( {'query': self._build_biomart_gene_query(txid)}) conn = http.client.HTTPConnection(ENS_URL) biomart_subdir = '/biomart/martservice?' conn.request("GET", biomart_subdir + params) resp = conn.getresponse() if resp.getcode() != 200: LOG.error("Got non-200 response code (%i) while retrieving %s from %s", resp.getcode(), params, ENS_URL) with open(loc_file, 'wb') as bin_writer: bin_writer.write(resp.read()) # I'm omitting the params here because they are several hundred characters # long and also seem to get munged by the time they get to the UI src_url = "http://" + ENS_URL + biomart_subdir self.dataset.set_ingest_source(src_url) self.dataset.set_ingest_source_file_version_retrieved_on( src_url, datetime.today().strftime('%Y-%m-%d'))
Example #26
Source File: rule.py From aswan with GNU Lesser General Public License v2.1 | 5 votes |
def persist(self): id_count_map = deepcopy(self.id_count_map) today = datetime.today() today_str = today.strftime('%Y%m%d') redis_hash_key = self.redis_hash_key_temp.format(today_str) try: for k, v in id_count_map.items(): self.conn.hincrby(redis_hash_key, k, v) except redis.RedisError as e: logger.error('incr access_count failed', exc_info=e) return # 全部写入之后再进行扣减 for k, v in id_count_map.items(): self.id_count_map[k] -= v
Example #27
Source File: wallet_manager.py From ontology-python-sdk with GNU Lesser General Public License v3.0 | 5 votes |
def create_wallet_file(self, wallet_path: str = ''): if not isinstance(wallet_path, str): raise SDKException(ErrorCode.require_str_params) if wallet_path != '': self.__wallet_path = wallet_path if not path.isfile(self.__wallet_path): self.wallet_in_mem.create_time = datetime.today().strftime("%Y-%m-%d %H:%M:%S") self.save() else: raise SDKException(ErrorCode.other_error('Wallet file has existed.'))
Example #28
Source File: test_kafka_msg_handler.py From koku with GNU Affero General Public License v3.0 | 5 votes |
def test_create_manifest_entries(self): """Test to create manifest entries.""" report_meta = { "schema_name": "test_schema", "manifest_id": "1", "provider_uuid": uuid.uuid4(), "provider_type": "OCP", "compression": "UNCOMPRESSED", "file": "/path/to/file.csv", "date": datetime.today(), "uuid": uuid.uuid4(), } with patch.object(OCPReportDownloader, "_prepare_db_manifest_record", return_value=1): self.assertEqual(1, msg_handler.create_manifest_entries(report_meta, "test_request_id"))
Example #29
Source File: test_azure_services.py From koku with GNU Affero General Public License v3.0 | 5 votes |
def setUp(self): """Set up each test.""" super().setUp() self.subscription_id = FAKE.uuid4() self.tenant_id = FAKE.uuid4() self.client_id = FAKE.uuid4() self.client_secret = FAKE.word() self.resource_group_name = FAKE.word() self.storage_account_name = FAKE.word() self.container_name = FAKE.word() self.current_date_time = datetime.today() self.export_directory = FAKE.word()
Example #30
Source File: certbot_generator.py From platform with GNU General Public License v3.0 | 5 votes |
def expiry_date_string_to_days(expiry, today=datetime.today()): expiry_date = datetime.strptime(expiry, "%Y%m%d%H%M%SZ") return (expiry_date - today).days