本文整理匯總了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))
示例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
示例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)
示例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
示例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
示例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})
示例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
)
示例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
示例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
示例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)
示例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'
)
示例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))
示例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))
示例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)
示例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