Python datetime.utcnow() Examples
The following are 30
code examples of datetime.utcnow().
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
, or try the search function
.
Example #1
Source File: context.py From upvote with Apache License 2.0 | 6 votes |
def stable_utcnow(): """Returns a current datetime.utcnow() that doesn't change during a request. You can use stable_utcnow to make sure that timedeltas computed against utcnow in various areas of your code are consistent with each other without having to inject an explicit datetime into each one. Returns: A datetime object that falls between the start of the current request and live_utcnow(), and is the same on repeated calls during the same request. """ # Environment variables are wiped between requests and module variables aren't if not os.getenv(_STABLE_UTCNOW_ENV_MARKER_NAME, None): SetStableUtcNowForTesting(live_utcnow()) return _stable_utcnow
Example #2
Source File: test_pip_checker.py From cloud-opensource-python with Apache License 2.0 | 6 votes |
def exec_run(self, cmd, stdout=True, stderr=True): from datetime import datetime _stdout = subprocess.PIPE if stdout else None _stderr = subprocess.PIPE if stderr else None result = subprocess.run( cmd, stderr=_stderr, stdout=_stdout) output = result.stdout if stdout else b'' output += result.stderr if stderr else b'' current_time = timestamp_to_seconds( datetime.utcnow().isoformat() + 'Z') duration = current_time - self.start_time if duration > pip_checker.TIME_OUT: result.returncode = 137 output = b'' return result.returncode, output
Example #3
Source File: importers.py From prospector with GNU General Public License v3.0 | 6 votes |
def set_last_updated(self, time=None): """ Sets the last_updated field of the object being imported to time. @arg time datetime object representing what last_updated should be set to. Defaults to datetime.utcnow() """ if not hasattr(self.object, 'last_updated'): return last_updated = datetime.datetime.utcnow() if time is None else time if self.object.last_updated != last_updated: logger.info("Setting last_updated on %s to %s", self.object, last_updated) self.object.last_updated = last_updated self.object.save()
Example #4
Source File: auth.py From qingcloud-sdk-python with Apache License 2.0 | 6 votes |
def get_auth_parameters(self, method, auth_path, expires, params=None, headers=None): params = params or [] auth_params = [ ("X-QS-Algorithm", "QS-HMAC-SHA256"), ("X-QS-Credential", self.qy_access_key_id), ("X-QS-Date", datetime.utcnow().strftime("%Y%m%dT%H%M%SZ")), ("X-QS-Expires", str(expires)), ] signature = self._generate_signature(method, auth_path, params + auth_params, headers or {}) auth_params.append(("X-QS-Signature", signature)) return dict(auth_params)
Example #5
Source File: time.py From bot with MIT License | 6 votes |
def until_expiration( expiry: Optional[str], now: Optional[datetime.datetime] = None, max_units: int = 2 ) -> Optional[str]: """ Get the remaining time until infraction's expiration, in a human-readable version of the relativedelta. Returns a human-readable version of the remaining duration between datetime.utcnow() and an expiry. Unlike `humanize_delta`, this function will force the `precision` to be `seconds` by not passing it. `max_units` specifies the maximum number of units of time to include (e.g. 1 may include days but not hours). By default, max_units is 2. """ if not expiry: return None now = now or datetime.datetime.utcnow() since = dateutil.parser.isoparse(expiry).replace(tzinfo=None, microsecond=0) if since < now: return None return humanize_delta(relativedelta(since, now), max_units=max_units)
Example #6
Source File: test_time_functions.py From tripleo-common with Apache License 2.0 | 6 votes |
def mock_now(dt): """Context manager for mocking out datetime.utcnow() in unit tests. Example: with mock_now(datetime.datetime(2011, 2, 3, 10, 11)): assert datetime.datetime.utcnow() \ == datetime.datetime(2011, 2, 3, 10, 11) """ class MockDatetime(datetime.datetime): @classmethod def utcnow(cls): return dt real_datetime = datetime.datetime datetime.datetime = MockDatetime try: yield datetime.datetime finally: datetime.datetime = real_datetime
Example #7
Source File: test_datetime.py From CTFCrackTools-V2 with GNU General Public License v3.0 | 5 votes |
def test_utcnow(self): import time # Call it a success if utcnow() and utcfromtimestamp() are within # a second of each other. tolerance = timedelta(seconds=1) for dummy in range(3): from_now = self.theclass.utcnow() from_timestamp = self.theclass.utcfromtimestamp(time.time()) if abs(from_timestamp - from_now) <= tolerance: break # Else try again a few times. self.assertTrue(abs(from_timestamp - from_now) <= tolerance)
Example #8
Source File: test_datetime.py From CTFCrackTools-V2 with GNU General Public License v3.0 | 5 votes |
def test_tzinfo_now(self): meth = self.theclass.now # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up). base = meth() # Try with and without naming the keyword. off42 = FixedOffset(42, "42") another = meth(off42) again = meth(tz=off42) self.assertTrue(another.tzinfo is again.tzinfo) self.assertEqual(another.utcoffset(), timedelta(minutes=42)) # Bad argument with and w/o naming the keyword. self.assertRaises(TypeError, meth, 16) self.assertRaises(TypeError, meth, tzinfo=16) # Bad keyword name. self.assertRaises(TypeError, meth, tinfo=off42) # Too many args. self.assertRaises(TypeError, meth, off42, off42) # We don't know which time zone we're in, and don't have a tzinfo # class to represent it, so seeing whether a tz argument actually # does a conversion is tricky. weirdtz = FixedOffset(timedelta(hours=15, minutes=58), "weirdtz", 0) utc = FixedOffset(0, "utc", 0) for dummy in range(3): now = datetime.now(weirdtz) self.assertTrue(now.tzinfo is weirdtz) utcnow = datetime.utcnow().replace(tzinfo=utc) now2 = utcnow.astimezone(weirdtz) if abs(now - now2) < timedelta(seconds=30): break # Else the code is broken, or more than 30 seconds passed between # calls; assuming the latter, just try again. else: # Three strikes and we're out. self.fail("utcnow(), now(tz), or astimezone() may be broken")
Example #9
Source File: test_datetime.py From CTFCrackTools-V2 with GNU General Public License v3.0 | 5 votes |
def test_tzinfo_utcnow(self): meth = self.theclass.utcnow # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up). base = meth() # Try with and without naming the keyword; for whatever reason, # utcnow() doesn't accept a tzinfo argument. off42 = FixedOffset(42, "42") self.assertRaises(TypeError, meth, off42) self.assertRaises(TypeError, meth, tzinfo=off42)
Example #10
Source File: dogtag.py From barbican with Apache License 2.0 | 5 votes |
def expiration(self): if self._expiration is None: try: with open(self._expiration_data_path) as expiration_fh: self._expiration = datetime.datetime.strptime( expiration_fh.read(), "%Y-%m-%d %H:%M:%S.%f" ) except (ValueError, TypeError): LOG.warning("Invalid data read from expiration file") self.expiration = datetime.utcnow() return self._expiration
Example #11
Source File: test_datetime.py From CTFCrackTools with GNU General Public License v3.0 | 5 votes |
def test_utcnow(self): import time # Call it a success if utcnow() and utcfromtimestamp() are within # a second of each other. tolerance = timedelta(seconds=1) for dummy in range(3): from_now = self.theclass.utcnow() from_timestamp = self.theclass.utcfromtimestamp(time.time()) if abs(from_timestamp - from_now) <= tolerance: break # Else try again a few times. self.assertTrue(abs(from_timestamp - from_now) <= tolerance)
Example #12
Source File: context.py From upvote with Apache License 2.0 | 5 votes |
def live_utcnow(): """Returns datetime.datetime.utcnow(), but can be overridden for testing.""" return _live_utcnow or datetime.datetime.utcnow()
Example #13
Source File: test_datetime.py From CTFCrackTools with GNU General Public License v3.0 | 5 votes |
def test_tzinfo_now(self): meth = self.theclass.now # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up). base = meth() # Try with and without naming the keyword. off42 = FixedOffset(42, "42") another = meth(off42) again = meth(tz=off42) self.assertTrue(another.tzinfo is again.tzinfo) self.assertEqual(another.utcoffset(), timedelta(minutes=42)) # Bad argument with and w/o naming the keyword. self.assertRaises(TypeError, meth, 16) self.assertRaises(TypeError, meth, tzinfo=16) # Bad keyword name. self.assertRaises(TypeError, meth, tinfo=off42) # Too many args. self.assertRaises(TypeError, meth, off42, off42) # We don't know which time zone we're in, and don't have a tzinfo # class to represent it, so seeing whether a tz argument actually # does a conversion is tricky. weirdtz = FixedOffset(timedelta(hours=15, minutes=58), "weirdtz", 0) utc = FixedOffset(0, "utc", 0) for dummy in range(3): now = datetime.now(weirdtz) self.assertTrue(now.tzinfo is weirdtz) utcnow = datetime.utcnow().replace(tzinfo=utc) now2 = utcnow.astimezone(weirdtz) if abs(now - now2) < timedelta(seconds=30): break # Else the code is broken, or more than 30 seconds passed between # calls; assuming the latter, just try again. else: # Three strikes and we're out. self.fail("utcnow(), now(tz), or astimezone() may be broken")
Example #14
Source File: test_datetime.py From CTFCrackTools with GNU General Public License v3.0 | 5 votes |
def test_tzinfo_utcnow(self): meth = self.theclass.utcnow # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up). base = meth() # Try with and without naming the keyword; for whatever reason, # utcnow() doesn't accept a tzinfo argument. off42 = FixedOffset(42, "42") self.assertRaises(TypeError, meth, off42) self.assertRaises(TypeError, meth, tzinfo=off42)
Example #15
Source File: warranty_dell.py From warranty_check with MIT License | 5 votes |
def get_access_token(self, client_id, client_secret): access_token_request_url = "https://apigtwb2c.us.dell.com/auth/oauth/v2/token" timeout = 60 payload = { 'client_id': client_id, 'client_secret': client_secret, 'grant_type': 'client_credentials' } try: resp = requests.post(access_token_request_url, data=payload, timeout=timeout) msg = 'Status code: %s' % str(resp.status_code) if str(resp.status_code) == '400' or str(resp.status_code) == '401' or str(resp.status_code) == '404': print 'HTTP error. Message was: %s' % msg elif str(resp.status_code) == '500': print 'HTTP error. Message was: %s' % msg print 'token access services may be down, try again later...' print resp.text else: # assign access token and expiration to instance variables result = resp.json() self.access_token = "Bearer " + str(result['access_token']) self.expires_at = datetime.utcnow() + timedelta(seconds=int(result['expires_in'])) if self.debug > 1: print "Request Token Acquired" except requests.RequestException as e: self.error_msg(e)
Example #16
Source File: utils.py From luci-py with Apache License 2.0 | 5 votes |
def milliseconds_since_epoch(now): """Returns the number of milliseconds since unix epoch as an int.""" now = now or utcnow() return int(round((now - EPOCH).total_seconds() * 1000.))
Example #17
Source File: test_datetime.py From medicare-demo with Apache License 2.0 | 5 votes |
def test_utcnow(self): import time # Call it a success if utcnow() and utcfromtimestamp() are within # a second of each other. tolerance = timedelta(seconds=1) for dummy in range(3): from_now = self.theclass.utcnow() from_timestamp = self.theclass.utcfromtimestamp(time.time()) if abs(from_timestamp - from_now) <= tolerance: break # Else try again a few times. self.failUnless(abs(from_timestamp - from_now) <= tolerance)
Example #18
Source File: dogtag.py From barbican with Apache License 2.0 | 5 votes |
def __init__(self, conf=CONF): """Constructor - create the cert clients.""" connection = create_connection(conf, 'ca') self.certclient = pki.cert.CertClient(connection) self.simple_cmc_profile = conf.dogtag_plugin.simple_cmc_profile self.auto_approved_profiles = conf.dogtag_plugin.auto_approved_profiles self.working_dir = conf.dogtag_plugin.plugin_working_dir if not os.path.isdir(self.working_dir): os.mkdir(self.working_dir) self._expiration = None self._expiration_delta = conf.dogtag_plugin.ca_expiration_time self._expiration_data_path = os.path.join(self.working_dir, "expiration_data.txt") self._host_aid_path = os.path.join(self.working_dir, "host_aid.txt") self._host_aid = None if not os.path.isfile(self._expiration_data_path): self.expiration = datetime.datetime.utcnow() global subcas_available subcas_available = self._are_subcas_enabled_on_backend(connection) if subcas_available: self.authority_client = authority.AuthorityClient(connection) if not os.path.isfile(self._host_aid_path): self.host_aid = self.get_host_aid()
Example #19
Source File: test_pip_checker.py From cloud-opensource-python with Apache License 2.0 | 5 votes |
def run(self, base_image, command, detach=True, remove=False, auto_remove=False): from datetime import datetime self.start_time = timestamp_to_seconds( datetime.utcnow().isoformat() + 'Z') return self
Example #20
Source File: test_datetime.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_tzinfo_utcnow(self): meth = self.theclass.utcnow # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up). base = meth() # Try with and without naming the keyword; for whatever reason, # utcnow() doesn't accept a tzinfo argument. off42 = FixedOffset(42, "42") self.assertRaises(TypeError, meth, off42) self.assertRaises(TypeError, meth, tzinfo=off42)
Example #21
Source File: test_datetime.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_tzinfo_now(self): meth = self.theclass.now # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up). base = meth() # Try with and without naming the keyword. off42 = FixedOffset(42, "42") another = meth(off42) again = meth(tz=off42) self.assertIs(another.tzinfo, again.tzinfo) self.assertEqual(another.utcoffset(), timedelta(minutes=42)) # Bad argument with and w/o naming the keyword. self.assertRaises(TypeError, meth, 16) self.assertRaises(TypeError, meth, tzinfo=16) # Bad keyword name. self.assertRaises(TypeError, meth, tinfo=off42) # Too many args. self.assertRaises(TypeError, meth, off42, off42) # We don't know which time zone we're in, and don't have a tzinfo # class to represent it, so seeing whether a tz argument actually # does a conversion is tricky. weirdtz = FixedOffset(timedelta(hours=15, minutes=58), "weirdtz", 0) utc = FixedOffset(0, "utc", 0) for dummy in range(3): now = datetime.now(weirdtz) self.assertIs(now.tzinfo, weirdtz) utcnow = datetime.utcnow().replace(tzinfo=utc) now2 = utcnow.astimezone(weirdtz) if abs(now - now2) < timedelta(seconds=30): break # Else the code is broken, or more than 30 seconds passed between # calls; assuming the latter, just try again. else: # Three strikes and we're out. self.fail("utcnow(), now(tz), or astimezone() may be broken")
Example #22
Source File: test_datetime.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_utcnow(self): import time # Call it a success if utcnow() and utcfromtimestamp() are within # a second of each other. tolerance = timedelta(seconds=1) for dummy in range(3): from_now = self.theclass.utcnow() from_timestamp = self.theclass.utcfromtimestamp(time.time()) if abs(from_timestamp - from_now) <= tolerance: break # Else try again a few times. self.assertLessEqual(abs(from_timestamp - from_now), tolerance)
Example #23
Source File: dogtag.py From sgx-kms with Apache License 2.0 | 5 votes |
def get_ca_info(self): if not subcas_available: return super(DogtagCAPlugin, self).get_ca_info() self.expiration = (datetime.datetime.utcnow() + datetime.timedelta( days=int(self._expiration_delta))) ret = {} cas = self.authority_client.list_cas() for ca_data in cas.ca_list: if not ca_data.enabled: continue cert = self.authority_client.get_cert(ca_data.aid, "PEM") chain = self.authority_client.get_chain(ca_data.aid, "PEM") ca_info = { cm.INFO_NAME: ca_data.description, cm.INFO_CA_SIGNING_CERT: cert, cm.INFO_INTERMEDIATES: chain, cm.INFO_EXPIRATION: self.expiration.isoformat() } # handle the migration case. The top level CA should continue # to work as before if ca_data.is_host_authority: ret[self.get_default_ca_name()] = ca_info self.host_aid = ca_data.aid else: ret[ca_data.aid] = ca_info return ret
Example #24
Source File: dogtag.py From sgx-kms with Apache License 2.0 | 5 votes |
def expiration(self): if self._expiration is None: try: with open(self._expiration_data_path) as expiration_fh: self._expiration = datetime.datetime.strptime( expiration_fh.read(), "%Y-%m-%d %H:%M:%S.%f" ) except (ValueError, TypeError): LOG.warning(u._LI("Invalid data read from expiration file")) self.expiration = datetime.utcnow() return self._expiration
Example #25
Source File: dogtag.py From sgx-kms with Apache License 2.0 | 5 votes |
def __init__(self, conf=CONF): """Constructor - create the cert clients.""" connection = create_connection(conf, 'ca') self.certclient = pki.cert.CertClient(connection) self.simple_cmc_profile = conf.dogtag_plugin.simple_cmc_profile self.auto_approved_profiles = conf.dogtag_plugin.auto_approved_profiles self.working_dir = conf.dogtag_plugin.plugin_working_dir if not os.path.isdir(self.working_dir): os.mkdir(self.working_dir) self._expiration = None self._expiration_delta = conf.dogtag_plugin.ca_expiration_time self._expiration_data_path = os.path.join(self.working_dir, "expiration_data.txt") self._host_aid_path = os.path.join(self.working_dir, "host_aid.txt") self._host_aid = None if not os.path.isfile(self._expiration_data_path): self.expiration = datetime.datetime.utcnow() global subcas_available subcas_available = self._are_subcas_enabled_on_backend(connection) if subcas_available: self.authority_client = authority.AuthorityClient(connection) if not os.path.isfile(self._host_aid_path): self.host_aid = self.get_host_aid()
Example #26
Source File: utils.py From luci-py with Apache License 2.0 | 5 votes |
def milliseconds_since_epoch(now): """Returns the number of milliseconds since unix epoch as an int.""" now = now or utcnow() return int(round((now - EPOCH).total_seconds() * 1000.))
Example #27
Source File: utils.py From luci-py with Apache License 2.0 | 5 votes |
def time_time(): """Returns the equivalent of time.time() as mocked if applicable.""" return (utcnow() - EPOCH).total_seconds()
Example #28
Source File: utils.py From luci-py with Apache License 2.0 | 5 votes |
def utcnow(): """Returns datetime.utcnow(), used for testing. Use this function so it can be mocked everywhere. """ return datetime.datetime.utcnow()
Example #29
Source File: utils.py From luci-py with Apache License 2.0 | 5 votes |
def time_time(): """Returns the equivalent of time.time() as mocked if applicable.""" return (utcnow() - EPOCH).total_seconds()
Example #30
Source File: utils.py From luci-py with Apache License 2.0 | 5 votes |
def utcnow(): """Returns datetime.utcnow(), used for testing. Use this function so it can be mocked everywhere. """ return datetime.datetime.utcnow()