Python datetime.utcnow() Examples

The following are 30 code examples for showing how to use datetime.utcnow(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module datetime , or try the search function .

Example 1
Project: bot   Author: python-discord   File: time.py    License: MIT License 6 votes vote down vote up
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 2
Project: SparseSC   Author: microsoft   File: azure_batch_client.py    License: MIT License 6 votes vote down vote up
def build_output_sas_url(config, _blob_client):
    """
    build a sas token for the output container
    """

    sas_token = _blob_client.generate_container_shared_access_signature(
        config.CONTAINER_NAME,
        ContainerPermissions.READ
        + ContainerPermissions.WRITE
        + ContainerPermissions.DELETE
        + ContainerPermissions.LIST,
        datetime.datetime.utcnow() + datetime.timedelta(hours=config.STORAGE_ACCESS_DURATION_HRS),
        start=datetime.datetime.utcnow(),
    )

    _sas_url = "https://{}.blob.core.windows.net/{}?{}".format(
        config.STORAGE_ACCOUNT_NAME, config.CONTAINER_NAME, sas_token
    )
    return _sas_url 
Example 3
Project: prospector   Author: chaoss   File: importers.py    License: GNU General Public License v3.0 6 votes vote down vote up
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
Project: cloud-opensource-python   Author: GoogleCloudPlatform   File: test_pip_checker.py    License: Apache License 2.0 6 votes vote down vote up
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 5
Project: qingcloud-sdk-python   Author: yunify   File: auth.py    License: Apache License 2.0 6 votes vote down vote up
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 6
Project: upvote   Author: google   File: context.py    License: Apache License 2.0 6 votes vote down vote up
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 7
Project: tripleo-common   Author: openstack   File: test_time_functions.py    License: Apache License 2.0 6 votes vote down vote up
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 8
Project: bloop   Author: numberoverzero   File: types.py    License: MIT License 5 votes vote down vote up
def dynamo_dump(self, value, *, context, **kwargs):
        if value is None:
            return None
        if value.tzinfo is None:
            raise ValueError(
                "naive datetime instances are not supported.  You can set a timezone with either "
                "your_dt.replace(tzinfo=) or your_dt.astimezone(tz=).  WARNING: calling astimezone on a naive "
                "datetime will assume the naive datetime is in the system's timezone, even though "
                "datetime.utcnow() creates a naive object!  You almost certainly don't want to do that."
            )
        dt = value.astimezone(tz=datetime.timezone.utc)
        return dt.strftime(FIXED_ISO8601_FORMAT) 
Example 9
Project: bloop   Author: numberoverzero   File: types.py    License: MIT License 5 votes vote down vote up
def dynamo_dump(self, value, *, context, **kwargs):
        if value is None:
            return None
        if value.tzinfo is None:
            raise ValueError(
                "naive datetime instances are not supported.  You can set a timezone with either "
                "your_dt.replace(tzinfo=) or your_dt.astimezone(tz=).  WARNING: calling astimezone on a naive "
                "datetime will assume the naive datetime is in the system's timezone, even though "
                "datetime.utcnow() creates a naive object!  You almost certainly don't want to do that."
            )
        value = value.timestamp()
        return super().dynamo_dump(value, context=context, **kwargs) 
Example 10
Project: bot   Author: python-discord   File: time.py    License: MIT License 5 votes vote down vote up
def time_since(past_datetime: datetime.datetime, precision: str = "seconds", max_units: int = 6) -> str:
    """
    Takes a datetime and returns a human-readable string that describes how long ago that datetime was.

    precision specifies the smallest unit of time to include (e.g. "seconds", "minutes").
    max_units specifies the maximum number of units of time to include (e.g. 1 may include days but not hours).
    """
    now = datetime.datetime.utcnow()
    delta = abs(relativedelta(now, past_datetime))

    humanized = humanize_delta(delta, precision, max_units)

    return f"{humanized} ago" 
Example 11
Project: bot   Author: python-discord   File: time.py    License: MIT License 5 votes vote down vote up
def wait_until(time: datetime.datetime, start: Optional[datetime.datetime] = None) -> None:
    """
    Wait until a given time.

    :param time: A datetime.datetime object to wait until.
    :param start: The start from which to calculate the waiting duration. Defaults to UTC time.
    """
    delay = time - (start or datetime.datetime.utcnow())
    delay_seconds = delay.total_seconds()

    # Incorporate a small delay so we don't rapid-fire the event due to time precision errors
    if delay_seconds > 1.0:
        await asyncio.sleep(delay_seconds) 
Example 12
Project: bot   Author: python-discord   File: time.py    License: MIT License 5 votes vote down vote up
def format_infraction_with_duration(
    date_to: Optional[str],
    date_from: Optional[datetime.datetime] = None,
    max_units: int = 2,
    absolute: bool = True
) -> Optional[str]:
    """
    Return `date_to` formatted as a readable ISO-8601 with the humanized duration since `date_from`.

    `date_from` must be an ISO-8601 formatted timestamp. The duration is calculated as from
    `date_from` until `date_to` with a precision of seconds. If `date_from` is unspecified, the
    current time is used.

    `max_units` specifies the maximum number of units of time to include in the duration. For
    example, a value of 1 may include days but not hours.

    If `absolute` is True, the absolute value of the duration delta is used. This prevents negative
    values in the case that `date_to` is in the past relative to `date_from`.
    """
    if not date_to:
        return None

    date_to_formatted = format_infraction(date_to)

    date_from = date_from or datetime.datetime.utcnow()
    date_to = dateutil.parser.isoparse(date_to).replace(tzinfo=None, microsecond=0)

    delta = relativedelta(date_to, date_from)
    if absolute:
        delta = abs(delta)

    duration = humanize_delta(delta, max_units=max_units)
    duration_formatted = f" ({duration})" if duration else ""

    return f"{date_to_formatted}{duration_formatted}" 
Example 13
Project: SempoBlockchain   Author: teamsempo   File: processor.py    License: GNU General Public License v3.0 5 votes vote down vote up
def check_transaction_hash(self, tx_hash):

        print('watching txn: {} at {}'.format(tx_hash, datetime.datetime.utcnow()))

        tx_receipt = self.w3.eth.getTransactionReceipt(tx_hash)

        def print_and_return(return_dict):
            # Not printing here currently because the method above does it
            # print('{} for txn: {}'.format(return_dict.get('status'), tx_hash))
            return return_dict

        if tx_receipt is None:
            return print_and_return({'status': 'PENDING'})

        mined_date = str(datetime.datetime.utcnow())

        if tx_receipt.blockNumber is None:
            return print_and_return({'status': 'PENDING', 'message': 'Next Block'})

        if tx_receipt.status == 1:

            return print_and_return({
                'status': 'SUCCESS',
                'block': tx_receipt.blockNumber,
                'contract_address': tx_receipt.contractAddress,
                'mined_date': mined_date
            })

        else:
           return print_and_return({
               'status': 'FAILED',
               'error': 'Blockchain Error',
               'block': tx_receipt.blockNumber,
               'mined_date': mined_date
           }) 
Example 14
Project: ironpython2   Author: IronLanguages   File: test_datetime.py    License: Apache License 2.0 5 votes vote down vote up
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 15
Project: ironpython2   Author: IronLanguages   File: test_datetime.py    License: Apache License 2.0 5 votes vote down vote up
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 16
Project: ironpython2   Author: IronLanguages   File: test_datetime.py    License: Apache License 2.0 5 votes vote down vote up
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 17
Project: cloud-inquisitor   Author: RiotGames   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def get_resources(self):
        found_issues = self.get_known_resources_missing_tags()
        existing_issues = RequiredTagsIssue.get_all().items()
        known_issues = []
        fixed_issues = []

        for existing_issue_id, existing_issue in existing_issues:
            # Check if the existing issue is still persists
            resource = found_issues.pop(existing_issue_id, None)
            if resource:
                if resource['missing_tags'] != existing_issue.missing_tags:
                    existing_issue.set_property('missing_tags', resource['missing_tags'])
                if resource['notes'] != existing_issue.notes:
                    existing_issue.set_property('notes', resource['notes'])
                db.session.add(existing_issue.issue)
                known_issues.append(existing_issue)
            else:
                fixed_issues.append(existing_issue)

        new_issues = {}
        for resource_id, resource in found_issues.items():
            try:
                if (
                        (datetime.utcnow() - resource['resource'].resource_creation_date).total_seconds() // 3600
                ) >= self.grace_period:
                    new_issues[resource_id] = resource
            except Exception as ex:
                self.log.error(
                    'Failed to construct new issue {}, Error: {}'.format(resource_id, ex)
                )

        db.session.commit()
        return known_issues, new_issues, fixed_issues 
Example 18
Project: SparseSC   Author: microsoft   File: azure_batch_client.py    License: MIT License 5 votes vote down vote up
def upload_file_to_container(block_blob_client, container_name, file_path, duration_hours=24):
    """
    Uploads a local file to an Azure Blob storage container.

    :param block_blob_client: A blob service client.
    :type block_blob_client: `azure.storage.blob.BlockBlobService`
    :param str container_name: The name of the Azure Blob storage container.
    :param str file_path: The local path to the file.
    :rtype: `azure.batch.models.ResourceFile`
    :return: A ResourceFile initialized with a SAS URL appropriate for Batch
    tasks.
    """
    blob_name = os.path.basename(file_path)

    print("Uploading file {} to container [{}]...".format(file_path, container_name))

    block_blob_client.create_blob_from_path(container_name, blob_name, file_path)

    sas_token = block_blob_client.generate_blob_shared_access_signature(
        container_name,
        blob_name,
        permission=azureblob.BlobPermissions.READ,
        expiry=datetime.datetime.utcnow() + datetime.timedelta(hours=duration_hours),
    )

    sas_url = block_blob_client.make_blob_url(
        container_name, blob_name, sas_token=sas_token
    )

    return models.ResourceFile(http_url=sas_url, file_path=_CONTAINER_INPUT_FILE) 
Example 19
Project: BinderFilter   Author: dxwu   File: test_datetime.py    License: MIT License 5 votes vote down vote up
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 20
Project: BinderFilter   Author: dxwu   File: test_datetime.py    License: MIT License 5 votes vote down vote up
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 21
Project: BinderFilter   Author: dxwu   File: test_datetime.py    License: MIT License 5 votes vote down vote up
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 22
Project: Computable   Author: ktraunmueller   File: test_timeseries.py    License: MIT License 5 votes vote down vote up
def test_class_ops(self):
        _skip_if_no_pytz()
        import pytz

        def compare(x,y):
            self.assertEqual(int(Timestamp(x).value/1e9), int(Timestamp(y).value/1e9))

        compare(Timestamp.now(),datetime.now())
        compare(Timestamp.now('UTC'),datetime.now(pytz.timezone('UTC')))
        compare(Timestamp.utcnow(),datetime.utcnow())
        compare(Timestamp.today(),datetime.today()) 
Example 23
Project: oss-ftp   Author: aliyun   File: test_datetime.py    License: MIT License 5 votes vote down vote up
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 24
Project: oss-ftp   Author: aliyun   File: test_datetime.py    License: MIT License 5 votes vote down vote up
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 25
Project: oss-ftp   Author: aliyun   File: test_datetime.py    License: MIT License 5 votes vote down vote up
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 26
Project: prospector   Author: chaoss   File: importers.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, obj):
        self.object = obj
        self.earliest_point = datetime.datetime.utcnow()
        self.latest_point = None 
Example 27
Project: Protect4   Author: Aditmadzs   File: adit4.py    License: GNU General Public License v3.0 5 votes vote down vote up
def delete_log():
    ndt = datetime.now()
    for data in msg_dict:
        if (datetime.utcnow() - cTime_to_datetime(msg_dict[data]["createdTime"])) > datetime.timedelta(1):
            del msg_dict[msg_id] 
Example 28
Project: pyfixmsg   Author: Morgan-Stanley   File: fixmessage.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        """
        The constructor uses the ``dict()`` signature unmodified.
        You can set the following manually or through a factory function:

          * ``self.process`` an opaque value (to store the process that received or processed the message,
            defaults to empty string).
          * ``self.separator`` the default separator to use when parsing messages. Defaults to ``';'``
          * ``self.time`` the time the message has been created or received. Defaults to ``datetime.utcnow()``
          * ``self.recipient`` opaque value (to store for whom the message was intended)
          * ``self.direction`` Whether the message was received (``0``), sent (``1``) or unknown (``None``)
          * ``self.typed_values`` Whether the values in the message are typed. Defaults to ``False``
          * ``self.raw_message`` If constructed by class method ``from_buffer``, keep the original format
          * ``self.codec`` Default :py:class:`~pyfixmsg.codec.stringfix.Codec` to use to parse message. Defaults
            to a naive codec that doesn't support repeating groups
        """
        self.process = ''
        self.separator = ';'
        self.time = datetime.datetime.utcnow()
        self.recipient = ''
        self.direction = None
        self.typed_values = False
        self.raw_message = None
        self.codec = Codec()
        # Allows maintaining tag order if constructing msg from a FixFragment
        if args and isinstance(args[0], FixFragment):
            self.tag_order = getattr(args[0], 'tag_order', None)
        else:
            self.tag_order = None
        super(FixMessage, self).__init__(*args, **kwargs) 
Example 29
Project: Flask-P2P   Author: chalasr   File: app.py    License: MIT License 5 votes vote down vote up
def __init__(self, id, username=None):
        self.id = id
        self.username = username
        self.connected_at = datetime.utcnow()
        self.rooms = []
        self.messages = Queue() 
Example 30
Project: luci-py   Author: luci   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def utcnow():
  """Returns datetime.utcnow(), used for testing.

  Use this function so it can be mocked everywhere.
  """
  return datetime.datetime.utcnow()