当前位置: 首页>>代码示例>>Python>>正文


Python timezone.utc方法代码示例

本文整理汇总了Python中datetime.timezone.utc方法的典型用法代码示例。如果您正苦于以下问题:Python timezone.utc方法的具体用法?Python timezone.utc怎么用?Python timezone.utc使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在datetime.timezone的用法示例。


在下文中一共展示了timezone.utc方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_build

# 需要导入模块: from datetime import timezone [as 别名]
# 或者: from datetime.timezone import utc [as 别名]
def test_build(self):
        path = os.path.join(self.tmpdir, "ctnr", "Dockerfile")
        os.makedirs(os.path.dirname(path), exist_ok=True)
        with open(path, "w") as stream:
            stream.write("FROM alpine")

        builder = self.pclient.images.build(
            containerfiles=[path], tags=["alpine-unittest"]
        )
        self.assertIsNotNone(builder)

        *_, last_element = builder()  # drain the builder generator
        # Each element from builder is a tuple (line, image)
        img = last_element[1]

        self.assertIsNotNone(img)
        self.assertIn("localhost/alpine-unittest:latest", img.repoTags)
        self.assertLess(
            podman.datetime_parse(img.created), datetime.now(timezone.utc)
        ) 
开发者ID:containers,项目名称:python-podman,代码行数:22,代码来源:test_images.py

示例2: commit

# 需要导入模块: from datetime import timezone [as 别名]
# 或者: from datetime.timezone import utc [as 别名]
def commit(self) -> None:
        """
        Commit the transaction with a fixed transaction id.

        A read transaction can call commit() any number of times, while a write transaction can only use the
        same tx_id for 10 minutes from the first call.
        """
        now = datetime.now(timezone.utc)
        if self.first_commit_at is None:
            self.first_commit_at = now

        if self.mode == "r":
            response = self.engine.session.transaction_read(self._request)
        elif self.mode == "w":
            if now - self.first_commit_at > MAX_TOKEN_LIFETIME:
                raise TransactionTokenExpired
            response = self.engine.session.transaction_write(self._request, self.tx_id)
        else:
            raise ValueError(f"unrecognized mode {self.mode}")

        self._handle_response(response) 
开发者ID:numberoverzero,项目名称:bloop,代码行数:23,代码来源:transactions.py

示例3: test_write_commit

# 需要导入模块: from datetime import timezone [as 别名]
# 或者: from datetime.timezone import utc [as 别名]
def test_write_commit(wx, session):
    calls = {
        "saved": 0,
        "deleted": 0
    }

    @object_saved.connect
    def on_saved(*_, **__):
        calls["saved"] += 1

    @object_deleted.connect
    def on_deleted(*_, **__):
        calls["deleted"] += 1

    now = datetime.now(timezone.utc)
    wx.commit()

    session.transaction_write.assert_called_once_with(wx._request, wx.tx_id)
    assert (wx.first_commit_at - now) <= timedelta(seconds=1)
    assert calls["saved"] == 1
    assert calls["deleted"] == 1 
开发者ID:numberoverzero,项目名称:bloop,代码行数:23,代码来源:test_transactions.py

示例4: __new__

# 需要导入模块: from datetime import timezone [as 别名]
# 或者: from datetime.timezone import utc [as 别名]
def __new__(cls, offset, name=_Omitted):
            if not isinstance(offset, timedelta):
                raise TypeError("offset must be a timedelta")
            if name is cls._Omitted:
                if not offset:
                    return cls.utc
                name = None
            elif not isinstance(name, str):
                raise TypeError("name must be a string")
            if not cls._minoffset <= offset <= cls._maxoffset:
                raise ValueError(
                    "offset must be a timedelta "
                    "strictly between -timedelta(hours=24) and "
                    "timedelta(hours=24)."
                )
            return cls._create(offset, name) 
开发者ID:sdispater,项目名称:tomlkit,代码行数:18,代码来源:_compat.py

示例5: __repr__

# 需要导入模块: from datetime import timezone [as 别名]
# 或者: from datetime.timezone import utc [as 别名]
def __repr__(self):
            """Convert to formal string, for repr().

            >>> tz = timezone.utc
            >>> repr(tz)
            'datetime.timezone.utc'
            >>> tz = timezone(timedelta(hours=-5), 'EST')
            >>> repr(tz)
            "datetime.timezone(datetime.timedelta(-1, 68400), 'EST')"
            """
            if self is self.utc:
                return "datetime.timezone.utc"
            if self._name is None:
                return "%s.%s(%r)" % (
                    self.__class__.__module__,
                    self.__class__.__name__,
                    self._offset,
                )
            return "%s.%s(%r, %r)" % (
                self.__class__.__module__,
                self.__class__.__name__,
                self._offset,
                self._name,
            ) 
开发者ID:sdispater,项目名称:tomlkit,代码行数:26,代码来源:_compat.py

示例6: test_documents_are_ordered_by_modified_at_by_default

# 需要导入模块: from datetime import timezone [as 别名]
# 或者: from datetime.timezone import utc [as 别名]
def test_documents_are_ordered_by_modified_at_by_default(app):
    doc3 = DocumentFactory()
    doc1 = DocumentFactory()
    doc2 = DocumentFactory()
    # Update without calling save (which would override modified_at).
    Document.objects.filter(pk=doc1.pk).update(
        modified_at=datetime(2016, 6, 26, 16, 17, tzinfo=timezone.utc))
    Document.objects.filter(pk=doc2.pk).update(
        modified_at=datetime(2016, 6, 26, 16, 16, tzinfo=timezone.utc))
    Document.objects.filter(pk=doc3.pk).update(
        modified_at=datetime(2016, 6, 26, 16, 15, tzinfo=timezone.utc))
    response = app.get(reverse('mediacenter:index'))
    titles = response.pyquery.find('.document-list h3')
    assert doc1.title in titles[0].text_content()
    assert doc2.title in titles[1].text_content()
    assert doc3.title in titles[2].text_content() 
开发者ID:ideascube,项目名称:ideascube,代码行数:18,代码来源:test_views.py

示例7: test_should_take_sort_parameter_into_account

# 需要导入模块: from datetime import timezone [as 别名]
# 或者: from datetime.timezone import utc [as 别名]
def test_should_take_sort_parameter_into_account(app):
    doc3 = DocumentFactory()
    doc1 = DocumentFactory()
    doc2 = DocumentFactory()
    # Update without calling save (which would override modified_at).
    Document.objects.filter(pk=doc1.pk).update(
        modified_at=datetime(2016, 6, 26, 16, 17, tzinfo=timezone.utc))
    Document.objects.filter(pk=doc2.pk).update(
        modified_at=datetime(2016, 6, 26, 16, 16, tzinfo=timezone.utc))
    Document.objects.filter(pk=doc3.pk).update(
        modified_at=datetime(2016, 6, 26, 16, 15, tzinfo=timezone.utc))
    response = app.get(reverse('mediacenter:index'), params={'sort': 'asc'})
    titles = response.pyquery.find('.document-list h3')
    assert doc3.title in titles[0].text_content()
    assert doc2.title in titles[1].text_content()
    assert doc1.title in titles[2].text_content() 
开发者ID:ideascube,项目名称:ideascube,代码行数:18,代码来源:test_views.py

示例8: test_configuration

# 需要导入模块: from datetime import timezone [as 别名]
# 或者: from datetime.timezone import utc [as 别名]
def test_configuration(value, user):
    fakenow = datetime.now(tz=timezone.utc)
    assert Configuration.objects.count() == 0

    with freezegun.freeze_time(fakenow):
        Configuration(
            namespace='tests', key='setting1', value=value, actor=user).save()

    assert Configuration.objects.count() == 1

    configuration = Configuration.objects.first()
    assert configuration.namespace == 'tests'
    assert configuration.key == 'setting1'
    assert configuration.value == value
    assert configuration.actor == user
    assert configuration.date == fakenow
    assert str(configuration) == 'tests.setting1=%r' % value 
开发者ID:ideascube,项目名称:ideascube,代码行数:19,代码来源:test_models.py

示例9: test_books_are_ordered_by_created_at_by_default

# 需要导入模块: from datetime import timezone [as 别名]
# 或者: from datetime.timezone import utc [as 别名]
def test_books_are_ordered_by_created_at_by_default(app):
    book3 = BookFactory()
    book1 = BookFactory()
    book2 = BookFactory()
    BookSpecimenFactory(item=book1)
    BookSpecimenFactory(item=book2)
    BookSpecimenFactory(item=book3)
    # Update without calling save (which would not honour created_at).
    Book.objects.filter(pk=book1.pk).update(
        created_at=datetime(2016, 6, 26, 16, 17, tzinfo=timezone.utc))
    Book.objects.filter(pk=book2.pk).update(
        created_at=datetime(2016, 6, 26, 16, 16, tzinfo=timezone.utc))
    Book.objects.filter(pk=book3.pk).update(
        created_at=datetime(2016, 6, 26, 16, 15, tzinfo=timezone.utc))
    response = app.get(reverse('library:index'))
    titles = response.pyquery.find('.book-list h3')
    assert book1.name in titles[0].text_content()
    assert book2.name in titles[1].text_content()
    assert book3.name in titles[2].text_content() 
开发者ID:ideascube,项目名称:ideascube,代码行数:21,代码来源:test_views.py

示例10: test_should_take_sort_parameter_into_account

# 需要导入模块: from datetime import timezone [as 别名]
# 或者: from datetime.timezone import utc [as 别名]
def test_should_take_sort_parameter_into_account(app):
    book3 = BookFactory()
    book1 = BookFactory()
    book2 = BookFactory()
    BookSpecimenFactory(item=book1)
    BookSpecimenFactory(item=book2)
    BookSpecimenFactory(item=book3)
    # Update without calling save (which would not honour created_at).
    Book.objects.filter(pk=book1.pk).update(
        created_at=datetime(2016, 6, 26, 16, 17, tzinfo=timezone.utc))
    Book.objects.filter(pk=book2.pk).update(
        created_at=datetime(2016, 6, 26, 16, 16, tzinfo=timezone.utc))
    Book.objects.filter(pk=book3.pk).update(
        created_at=datetime(2016, 6, 26, 16, 15, tzinfo=timezone.utc))
    response = app.get(reverse('library:index'), params={'sort': 'asc'})
    titles = response.pyquery.find('.book-list h3')
    assert book3.name in titles[0].text_content()
    assert book2.name in titles[1].text_content()
    assert book1.name in titles[2].text_content() 
开发者ID:ideascube,项目名称:ideascube,代码行数:21,代码来源:test_views.py

示例11: test_signers_generate_db_auth_token

# 需要导入模块: from datetime import timezone [as 别名]
# 或者: from datetime.timezone import utc [as 别名]
def test_signers_generate_db_auth_token(rds_client):
    hostname = 'prod-instance.us-east-1.rds.amazonaws.com'
    port = 3306
    username = 'someusername'
    clock = datetime.datetime(2016, 11, 7, 17, 39, 33, tzinfo=timezone.utc)

    with mock.patch('datetime.datetime') as dt:
        dt.utcnow.return_value = clock
        result = await aiobotocore.signers.generate_db_auth_token(
            rds_client, hostname, port, username)

        result2 = await rds_client.generate_db_auth_token(
            hostname, port, username)

    # A scheme needs to be appended to the beginning or urlsplit may fail
    # on certain systems.
    assert result.startswith(
        'prod-instance.us-east-1.rds.amazonaws.com:3306/?AWSAccessKeyId=xxx&')
    assert result2.startswith(
        'prod-instance.us-east-1.rds.amazonaws.com:3306/?AWSAccessKeyId=xxx&') 
开发者ID:aio-libs,项目名称:aiobotocore,代码行数:22,代码来源:test_signers.py

示例12: test_load_dates_timezones

# 需要导入模块: from datetime import timezone [as 别名]
# 或者: from datetime.timezone import utc [as 别名]
def test_load_dates_timezones():
    from dataflows import Flow, checkpoint
    from datetime import datetime, timezone
    import shutil

    dates = [
        datetime.now(),
        datetime.now(timezone.utc).astimezone()
    ]

    shutil.rmtree('.checkpoints/test_load_dates_timezones', ignore_errors=True)

    Flow(
        [{'date': d.date(), 'datetime': d} for d in dates],
        checkpoint('test_load_dates_timezones')
    ).process()

    results = Flow(
        checkpoint('test_load_dates_timezones')
    ).results()

    assert list(map(lambda x: x['date'], results[0][0])) == \
        list(map(lambda x: x.date(), dates))
    assert list(map(lambda x: x['datetime'], results[0][0])) == \
        list(map(lambda x: x, dates)) 
开发者ID:datahq,项目名称:dataflows,代码行数:27,代码来源:test_lib.py

示例13: reset

# 需要导入模块: from datetime import timezone [as 别名]
# 或者: from datetime.timezone import utc [as 别名]
def reset(self, variantId, buildId, resultHash):
        self.__variantId = variantId
        self.__buildId = buildId
        self.__resultHash = resultHash
        self.__recipes = None
        self.__defines = {}
        u = platform.uname()
        self.__build = {
            'sysname'  : u.system,
            'nodename' : u.node,
            'release'  : u.release,
            'version'  : u.version,
            'machine'  : u.machine,
            'date'     : datetime.now(timezone.utc).isoformat(),
        }
        osRelease = self.__getOsRelease()
        if osRelease is not None:
            self.__build['os-release'] = osRelease
        self.__env = ""
        self.__metaEnv = {}
        self.__scms = []
        self.__deps = []
        self.__tools = {}
        self.__sandbox = None
        self.__id = None 
开发者ID:BobBuildTool,项目名称:bob,代码行数:27,代码来源:audit.py

示例14: parse_tweets

# 需要导入模块: from datetime import timezone [as 别名]
# 或者: from datetime.timezone import utc [as 别名]
def parse_tweets(raw_tweets, source, now=None):
    """
        Parses a list of raw tweet lines from a twtxt file
        and returns a list of :class:`Tweet` objects.

        :param list raw_tweets: list of raw tweet lines
        :param Source source: the source of the given tweets
        :param Datetime now: the current datetime

        :returns: a list of parsed tweets :class:`Tweet` objects
        :rtype: list
    """
    if now is None:
        now = datetime.now(timezone.utc)

    tweets = []
    for line in raw_tweets:
        try:
            tweet = parse_tweet(line, source, now)
        except (ValueError, OverflowError) as e:
            logger.debug("{0} - {1}".format(source.url, e))
        else:
            tweets.append(tweet)

    return tweets 
开发者ID:buckket,项目名称:twtxt,代码行数:27,代码来源:parser.py

示例15: parse_tweet

# 需要导入模块: from datetime import timezone [as 别名]
# 或者: from datetime.timezone import utc [as 别名]
def parse_tweet(raw_tweet, source, now=None):
    """
        Parses a single raw tweet line from a twtxt file
        and returns a :class:`Tweet` object.

        :param str raw_tweet: a single raw tweet line
        :param Source source: the source of the given tweet
        :param Datetime now: the current datetime

        :returns: the parsed tweet
        :rtype: Tweet
    """
    if now is None:
        now = datetime.now(timezone.utc)

    raw_created_at, text = raw_tweet.split("\t", 1)
    created_at = parse_iso8601(raw_created_at)

    if created_at > now:
        raise ValueError("Tweet is from the future")

    return Tweet(click.unstyle(text.strip()), created_at, source) 
开发者ID:buckket,项目名称:twtxt,代码行数:24,代码来源:parser.py


注:本文中的datetime.timezone.utc方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。