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


Python datetime.utcfromtimestamp方法代码示例

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


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

示例1: logs

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcfromtimestamp [as 别名]
def logs(args):
    if args.log_group and (args.log_stream or args.start_time or args.end_time):
        if args.export and args.print_s3_urls:
            return ["s3://{}/{}".format(f.bucket_name, f.key) for f in export_log_files(args)]
        elif args.export:
            return export_and_print_log_events(args)
        else:
            return print_log_events(args)
    table = []
    group_cols = ["logGroupName"]
    stream_cols = ["logStreamName", "lastIngestionTime", "storedBytes"]
    args.columns = group_cols + stream_cols
    for group in paginate(clients.logs.get_paginator("describe_log_groups")):
        if args.log_group and group["logGroupName"] != args.log_group:
            continue
        n = 0
        for stream in paginate(clients.logs.get_paginator("describe_log_streams"),
                               logGroupName=group["logGroupName"], orderBy="LastEventTime", descending=True):
            now = datetime.utcnow().replace(microsecond=0)
            stream["lastIngestionTime"] = now - datetime.utcfromtimestamp(stream.get("lastIngestionTime", 0) // 1000)
            table.append(dict(group, **stream))
            n += 1
            if n >= args.max_streams_per_group:
                break
    page_output(tabulate(table, args)) 
开发者ID:kislyuk,项目名称:aegea,代码行数:27,代码来源:logs.py

示例2: test_create_message

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcfromtimestamp [as 别名]
def test_create_message(self):
        message = SMB2CloseResponse()
        message['creation_time'] = datetime.utcfromtimestamp(0)
        message['last_access_time'] = datetime.utcfromtimestamp(0)
        message['last_write_time'] = datetime.utcfromtimestamp(0)
        message['change_time'] = datetime.utcfromtimestamp(0)
        expected = b"\x3c\x00" \
                   b"\x00\x00" \
                   b"\x00\x00\x00\x00" \
                   b"\x00\x80\x3E\xD5\xDE\xB1\x9D\x01" \
                   b"\x00\x80\x3E\xD5\xDE\xB1\x9D\x01" \
                   b"\x00\x80\x3E\xD5\xDE\xB1\x9D\x01" \
                   b"\x00\x80\x3E\xD5\xDE\xB1\x9D\x01" \
                   b"\x00\x00\x00\x00\x00\x00\x00\x00" \
                   b"\x00\x00\x00\x00\x00\x00\x00\x00" \
                   b"\x00\x00\x00\x00"
        actual = message.pack()
        assert len(actual) == 60
        assert actual == expected 
开发者ID:jborean93,项目名称:smbprotocol,代码行数:21,代码来源:test_open.py

示例3: start_data_processing

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcfromtimestamp [as 别名]
def start_data_processing():
    track['mode'] = 'METRIC'

    # set up shared api call info
    base_url = 'https://api.newrelic.com/'
    headers = {'X-Api-Key': agent_config_vars['api_key']}
    now = int(time.time())
    to_timestamp = datetime.utcfromtimestamp(now).isoformat()
    from_timestamp = datetime.utcfromtimestamp(now - agent_config_vars['run_interval']).isoformat()
    data = {
        'to': to_timestamp,
        'from': from_timestamp,
        'period': str(if_config_vars['samplingInterval'])
    }

    get_applications(base_url, headers, data) 
开发者ID:insightfinder,项目名称:InsightAgent,代码行数:18,代码来源:getmetrics_newrelic.py

示例4: get_revoked

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcfromtimestamp [as 别名]
def get_revoked(serial):
    if isinstance(serial, str):
        serial = int(serial, 16)
    path = os.path.join(config.REVOKED_DIR, "%040x.pem" % serial)
    with open(path, "rb") as fh:
        buf = fh.read()
        header, _, der_bytes = pem.unarmor(buf)
        cert = x509.Certificate.load(der_bytes)
        try:
            reason = getxattr(path, "user.revocation.reason").decode("ascii")
        except IOError: # TODO: make sure it's not required
            reason = "key_compromise"
        return path, buf, cert, \
            cert["tbs_certificate"]["validity"]["not_before"].native.replace(tzinfo=None), \
            cert["tbs_certificate"]["validity"]["not_after"].native.replace(tzinfo=None), \
            datetime.utcfromtimestamp(os.stat(path).st_ctime), \
            reason 
开发者ID:laurivosandi,项目名称:certidude,代码行数:19,代码来源:authority.py

示例5: test_cookie_expires

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcfromtimestamp [as 别名]
def test_cookie_expires(app, expires):
    expires = expires.replace(microsecond=0)
    cookies = {"test": "wait"}

    @app.get("/")
    def handler(request):
        response = text("pass")
        response.cookies["test"] = "pass"
        response.cookies["test"]["expires"] = expires
        return response

    request, response = app.test_client.get(
        "/", cookies=cookies, raw_cookies=True
    )
    cookie_expires = datetime.utcfromtimestamp(
        response.raw_cookies["test"].expires
    ).replace(microsecond=0)

    assert response.status == 200
    assert response.cookies["test"] == "pass"
    assert cookie_expires == expires 
开发者ID:huge-success,项目名称:sanic,代码行数:23,代码来源:test_cookies.py

示例6: extend_with_default

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcfromtimestamp [as 别名]
def extend_with_default(validator_class):
    validate_properties = validator_class.VALIDATORS["properties"]

    def set_defaults(validator, properties, instance, schema):
        for error in validate_properties(validator, properties, instance, schema):
            yield error

        for prop, subschema in properties.items():
            if "format" in subschema:
                if subschema['format'] == 'date-time' and instance.get(prop) is not None:
                    try:
                        datetime.utcfromtimestamp(rfc3339_to_timestamp(instance[prop]))
                    except Exception:
                        raise Exception('Error parsing property {}, value {}'
                                        .format(prop, instance[prop]))

    return validators.extend(validator_class, {"properties": set_defaults}) 
开发者ID:singer-io,项目名称:singer-tools,代码行数:19,代码来源:check_tap.py

示例7: get_video_meta

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcfromtimestamp [as 别名]
def get_video_meta(self):
        if self.__ffprobe_installed:
            try:
                command = FF_PROBE + [str(self.__full_path)]
                result = run(command, stdout=PIPE, check=True)
                out = str(result.stdout.decode("utf-8"))
                json = loads(out)
                t = json["format"]["tags"]["creation_time"]
                self.__createDate = Utils.string_to_date(t)
                self.got_meta = True
            except FileNotFoundError:
                # this means there is no ffprobe installed
                self.__ffprobe_installed = False
            except CalledProcessError:
                pass
            except KeyError:
                # ffprobe worked but there is no creation time in the JSON
                pass

        if not self.__createDate:
            # just use file date
            self.__createDate = datetime.utcfromtimestamp(
                self.__full_path.stat().st_mtime
            ) 
开发者ID:gilesknap,项目名称:gphotos-sync,代码行数:26,代码来源:LocalFilesMedia.py

示例8: get_image_date

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcfromtimestamp [as 别名]
def get_image_date(self):
        p_date = None
        if self.got_meta:
            try:
                # noinspection PyUnresolvedReferences
                p_date = Utils.string_to_date(self.__exif.datetime_original)
            except (AttributeError, ValueError, KeyError):
                try:
                    # noinspection PyUnresolvedReferences
                    p_date = Utils.string_to_date(self.__exif.datetime)
                except (AttributeError, ValueError, KeyError):
                    pass
        if not p_date:
            # just use file date
            p_date = datetime.utcfromtimestamp(self.__full_path.stat().st_mtime)
        self.__createDate = p_date 
开发者ID:gilesknap,项目名称:gphotos-sync,代码行数:18,代码来源:LocalFilesMedia.py

示例9: __init__

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcfromtimestamp [as 别名]
def __init__(self, author_filename, default_address, only_addresses = None, update_interval=timedelta(hours=1)):
    from ConfigParser import ConfigParser

    self.author_filename = author_filename
    self.default_address = default_address
    self.only_addresses = only_addresses
    self.update_interval = update_interval

    self.config_parser = ConfigParser()
    self.config_parser.read(self.author_filename)

    self.time_checked = datetime.utcnow()
    self.time_loaded  = datetime.utcfromtimestamp(os.path.getmtime(self.author_filename))

    if only_addresses:
      import re
      self.address_match_p = re.compile(only_addresses).match
    else:
      self.address_match_p = lambda addr: True 
开发者ID:llvm,项目名称:llvm-zorg,代码行数:21,代码来源:ConfigEmailLookup.py

示例10: _field_time_to_roaring

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcfromtimestamp [as 别名]
def _field_time_to_roaring(self, shard_width, clear):
        standard = Bitmap()
        bitmaps = {"": standard}
        time_quantum = self.field_time_quantum
        time_formats = self._time_formats
        for b in self.columns:
            bit = b.row_id * shard_width + b.column_id % shard_width
            standard.add(bit)
            for c in time_quantum:
                fmt = time_formats.get(c, "")
                view_name = datetime.utcfromtimestamp(b.timestamp).strftime(fmt)
                bmp = bitmaps.get(view_name)
                if not bmp:
                    bmp = Bitmap()
                    bitmaps[view_name] = bmp
                bmp.add(bit)
        return self._make_roaring_request(bitmaps, clear) 
开发者ID:pilosa,项目名称:python-pilosa,代码行数:19,代码来源:client.py

示例11: test_init

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcfromtimestamp [as 别名]
def test_init(self):
        self.assertEqual(self.inst.log_group_name, 'group_name')

        self.assertEqual(
            datetime.utcfromtimestamp(self.inst.start_ms // 1000),
            self.start_time
        )

        self.assertEqual(
            datetime.utcfromtimestamp(self.inst.end_ms // 1000),
            self.end_time
        )

        self.assertEqual(
            self.inst.paginator_kwargs['filterPattern'],
            'REJECT'
        ) 
开发者ID:obsrvbl,项目名称:flowlogs-reader,代码行数:19,代码来源:test_flowlogs_reader.py

示例12: test_class_ops_pytz

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcfromtimestamp [as 别名]
def test_class_ops_pytz(self):
        def compare(x, y):
            assert (int(Timestamp(x).value / 1e9) ==
                    int(Timestamp(y).value / 1e9))

        compare(Timestamp.now(), datetime.now())
        compare(Timestamp.now('UTC'), datetime.now(timezone('UTC')))
        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)) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:21,代码来源:test_timestamp.py

示例13: test_class_ops_dateutil

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcfromtimestamp [as 别名]
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)) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:21,代码来源:test_timestamp.py

示例14: test_date_parser_int_bug

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcfromtimestamp [as 别名]
def test_date_parser_int_bug(all_parsers):
    # see gh-3071
    parser = all_parsers
    data = ("posix_timestamp,elapsed,sys,user,queries,query_time,rows,"
            "accountid,userid,contactid,level,silo,method\n"
            "1343103150,0.062353,0,4,6,0.01690,3,"
            "12345,1,-1,3,invoice_InvoiceResource,search\n")

    result = parser.read_csv(
        StringIO(data), index_col=0, parse_dates=[0],
        date_parser=lambda x: datetime.utcfromtimestamp(int(x)))
    expected = DataFrame([[0.062353, 0, 4, 6, 0.01690, 3, 12345, 1, -1,
                           3, "invoice_InvoiceResource", "search"]],
                         columns=["elapsed", "sys", "user", "queries",
                                  "query_time", "rows", "accountid",
                                  "userid", "contactid", "level",
                                  "silo", "method"],
                         index=Index([Timestamp("2012-07-24 04:12:30")],
                                     name="posix_timestamp"))
    tm.assert_frame_equal(result, expected) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:22,代码来源:test_parse_dates.py

示例15: check_for_update

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcfromtimestamp [as 别名]
def check_for_update():
  if os.path.exists(FILE_UPDATE):
    mtime = os.path.getmtime(FILE_UPDATE)
    last = datetime.utcfromtimestamp(mtime).strftime('%Y-%m-%d')
    today = datetime.utcnow().strftime('%Y-%m-%d')
    if last == today:
      return
  try:
    with open(FILE_UPDATE, 'a'):
      os.utime(FILE_UPDATE, None)
    request = urllib2.Request(
      CORE_VERSION_URL,
      urllib.urlencode({'version': __version__}),
    )
    response = urllib2.urlopen(request)
    with open(FILE_UPDATE, 'w') as update_json:
      update_json.write(response.read())
  except (urllib2.HTTPError, urllib2.URLError):
    pass 
开发者ID:lipis,项目名称:github-stats,代码行数:21,代码来源:run.py


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