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


Python datetime.fromtimestamp方法代码示例

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


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

示例1: start_data_processing

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromtimestamp [as 别名]
def start_data_processing(thread_number):
    # run for run_interval +/- sampling_interval/2
    now_epoch = time.time() + (if_config_vars['sampling_interval'] / 2)
    start_epoch = now_epoch - if_config_vars['run_interval'] - if_config_vars['sampling_interval']
    get_metrics_to_collect()
    if 'REPLAY' in if_config_vars['project_type']:
        for replay_file in agent_config_vars['replay_sa_files']:
            # break into 1h segments
            for h in range(0, 24):
                get_sar_data(
                        '{:02d}:00:00'.format(h),
                        '{:02d}:59:59'.format(h),
                        replay_file)
                # send each chunk to keep mem usage low
                send_data_wrapper()
    else:
        get_sar_data(
                datetime.fromtimestamp(start_epoch).strftime('%H:%M:%S'),
                datetime.fromtimestamp(now_epoch).strftime('%H:%M:%S')) 
开发者ID:insightfinder,项目名称:InsightAgent,代码行数:21,代码来源:getmetrics_sar.py

示例2: refresh

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromtimestamp [as 别名]
def refresh(self):
        try:
            #open the data url
            self.req = urlopen(self.data_url)

            #read data from the url
            self.raw_data = self.req.read()

            #load in the json
            self.json_data = json.loads(self.raw_data.decode())

            #get time from json
            self.time = datetime.fromtimestamp(self.parser.time(self.json_data))

            #load all the aircarft
            self.aircraft = self.parser.aircraft_data(self.json_data, self.time)

        except Exception:
            print("exception in FlightData.refresh():")
            traceback.print_exc() 
开发者ID:kevinabrandon,项目名称:AboveTustin,代码行数:22,代码来源:flightdata.py

示例3: __new__

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromtimestamp [as 别名]
def __new__(cls, t, snap=0):
        if isinstance(t, (str, bytes)) and t.isdigit():
            t = int(t)
        if not isinstance(t, (str, bytes)):
            from dateutil.tz import tzutc
            return datetime.fromtimestamp(t // 1000, tz=tzutc())
        try:
            units = ["weeks", "days", "hours", "minutes", "seconds"]
            diffs = {u: float(t[:-1]) for u in units if u.startswith(t[-1])}
            if len(diffs) == 1:
                # Snap > 0 governs the rounding of units (hours, minutes and seconds) to 0 to improve cache performance
                snap_units = {u.rstrip("s"): 0 for u in units[units.index(list(diffs)[0]) + snap:]} if snap else {}
                snap_units.pop("day", None)
                snap_units.update(microsecond=0)
                ts = datetime.now().replace(**snap_units) + relativedelta(**diffs)
                cls._precision[ts] = snap_units
                return ts
            return dateutil_parse(t)
        except (ValueError, OverflowError, AssertionError):
            raise ValueError('Could not parse "{}" as a timestamp or time delta'.format(t)) 
开发者ID:kislyuk,项目名称:aegea,代码行数:22,代码来源:__init__.py

示例4: datetime

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromtimestamp [as 别名]
def datetime(self, field=None, val=None):
        """
        Returns a random datetime. If 'val' is passed, a datetime within two
        years of that date will be returned.
        """
        if val is None:
            def source():
                tzinfo = get_default_timezone() if settings.USE_TZ else None
                return datetime.fromtimestamp(randrange(1, 2100000000),
                                              tzinfo)
        else:
            def source():
                tzinfo = get_default_timezone() if settings.USE_TZ else None
                return datetime.fromtimestamp(int(val.strftime("%s")) +
                                              randrange(-365*24*3600*2, 365*24*3600*2),
                                              tzinfo)
        return self.get_allowed_value(source, field) 
开发者ID:BetterWorks,项目名称:django-anonymizer,代码行数:19,代码来源:base.py

示例5: __init__

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromtimestamp [as 别名]
def __init__(self):
        self.datetime_format = '%H:%M:%S %d/%m/%Y'
        self.__raw_boot_time = psutil.boot_time()
        self.__boot_time = datetime.fromtimestamp(self.raw_boot_time)
        self.__boot_time = self.__boot_time.strftime(self.datetime_format)
        self.__hostname = platform.node()
        self.__os = Computer.__get_os_name()
        self.__architecture = platform.machine()
        self.__python_version = '{} ver. {}'.format(
            platform.python_implementation(), platform.python_version()
        )
        self.__processor = Cpu(monitoring_latency=1)
        self.__nonvolatile_memory = NonvolatileMemory.instances_connected_devices(monitoring_latency=10)
        self.__nonvolatile_memory_devices = set(
            [dev_info.device for dev_info in self.__nonvolatile_memory]
        )
        self.__virtual_memory = VirtualMemory(monitoring_latency=1)
        self.__swap_memory = SwapMemory(monitoring_latency=1)
        self.__network_interface = NetworkInterface(monitoring_latency=3)
        super().__init__(monitoring_latency=3) 
开发者ID:it-geeks-club,项目名称:pyspectator,代码行数:22,代码来源:computer.py

示例6: save_webdriver_logs_by_type

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromtimestamp [as 别名]
def save_webdriver_logs_by_type(self, log_type, test_name):
        """Get webdriver logs of the specified type and write them to a log file

        :param log_type: browser, client, driver, performance, server, syslog, crashlog or logcat
        :param test_name: test that has generated these logs
        """
        try:
            logs = self.driver_wrapper.driver.get_log(log_type)
        except Exception:
            return

        if len(logs) > 0:
            from toolium.driver_wrappers_pool import DriverWrappersPool
            log_file_name = '{}_{}.txt'.format(get_valid_filename(test_name), log_type)
            log_file_name = os.path.join(DriverWrappersPool.logs_directory, log_file_name)
            with open(log_file_name, 'a+', encoding='utf-8') as log_file:
                driver_type = self.driver_wrapper.config.get('Driver', 'type')
                log_file.write(
                    u"\n{} '{}' test logs with driver = {}\n\n".format(datetime.now(), test_name, driver_type))
                for entry in logs:
                    timestamp = datetime.fromtimestamp(float(entry['timestamp']) / 1000.).strftime(
                        '%Y-%m-%d %H:%M:%S.%f')
                    log_file.write(u'{}\t{}\t{}\n'.format(timestamp, entry['level'], entry['message'].rstrip())) 
开发者ID:Telefonica,项目名称:toolium,代码行数:25,代码来源:driver_utils.py

示例7: __init__

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromtimestamp [as 别名]
def __init__(self, client, **data):
        self.client = client
        for attrib in self.ATTRIBUTES:
            val = data.get(attrib)
            if hasattr(self, 'TIMESTAMP_ATTRS'):
                if attrib in self.TIMESTAMP_ATTRS:
                    try:
                        val = datetime.fromtimestamp(int(val))
                    except ValueError:
                        log.warn(
                            'Could not cast %s for %s as datetime',
                            val, attrib
                        )
            setattr(self, attrib, val)
        self.object_id = getattr(self, self.RESOURCE_ID_ATTRIBUTE)
        for action in self.SIMPLE_ACTIONS:
            setattr(self, action, lambda x: self._simple_action(x))
            instance_method = getattr(self, action)
            try:
                instance_method.__defaults__ = (action,)
            except AttributeError:
                # ugh, for py2.7 compat
                instance_method.func_defaults = (action,) 
开发者ID:mdorn,项目名称:pyinstapaper,代码行数:25,代码来源:instapaper.py

示例8: parseATTime

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromtimestamp [as 别名]
def parseATTime(s, tzinfo=None):
    if tzinfo is None:
        tzinfo = pytz.utc
    s = s.strip().lower().replace('_', '').replace(',', '').replace(' ', '')
    if s.isdigit():
        if len(s) == 8 and int(s[:4]) > 1900 and int(
                s[4:6]) < 13 and int(s[6:]) < 32:
            pass  # Fall back because its not a timestamp, its YYYYMMDD form
        else:
            return datetime.fromtimestamp(int(s), tzinfo)
    elif ':' in s and len(s) == 13:
        return tzinfo.localize(datetime.strptime(s, '%H:%M%Y%m%d'), daylight)
    if '+' in s:
        ref, offset = s.split('+', 1)
        offset = '+' + offset
    elif '-' in s:
        ref, offset = s.split('-', 1)
        offset = '-' + offset
    else:
        ref, offset = s, ''
    return (
        parseTimeReference(ref) +
        parseTimeOffset(offset)).astimezone(tzinfo) 
开发者ID:moira-alert,项目名称:worker,代码行数:25,代码来源:attime.py

示例9: isSchedAllows

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromtimestamp [as 别名]
def isSchedAllows(self, ts):
        sched = self.struct.get('sched')
        if sched is None:
            return True

        timestamp = ts - ts % 60 - sched["tzOffset"] * 60
        date = datetime.fromtimestamp(timestamp)
        if not sched['days'][date.weekday()]['enabled']:
            return False
        day_start = datetime.fromtimestamp(timestamp - timestamp % (24 * 3600))
        start_datetime = day_start + timedelta(minutes=sched["startOffset"])
        end_datetime = day_start + timedelta(minutes=sched["endOffset"])
        if date < start_datetime:
            return False
        if date > end_datetime:
            return False
        return True 
开发者ID:moira-alert,项目名称:worker,代码行数:19,代码来源:trigger.py

示例10: get_log_for_test

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromtimestamp [as 别名]
def get_log_for_test(test_name, log_path, dt_format):
  """
  Gets the portion of the log file relevant to the test (i.e lies between the start and end times of the test).
  It is assumed that every line in the log file starts with a datetime following dtformat.
  :param test_name: the test name
  :param log_path: the absolute path to the log file
  :param dt_format: the format of the datetime in the log file. This could simply be an example datetime because
                   only the word count matters
  """
  word_count = len(dt_format.split())

  start_time = datetime.fromtimestamp(runtime.get_active_test_start_time(test_name))
  end_time = datetime.fromtimestamp(runtime.get_active_test_end_time(test_name))

  start_pos = _search_log_for_datetime(log_path, start_time, word_count)
  end_pos = _search_log_for_datetime(log_path, end_time, word_count, reverse=True)

  with open(log_path, 'r') as log:
    log.seek(start_pos)
    return log.read(end_pos - start_pos) 
开发者ID:linkedin,项目名称:Zopkio,代码行数:22,代码来源:test_utils.py

示例11: transactions

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromtimestamp [as 别名]
def transactions(self, hashes):
        res = self.raw_request('/get_transactions', {
                'txs_hashes': hashes,
                'decode_as_json': True})
        if res['status'] != 'OK':
            raise exceptions.BackendException(res['status'])
        txs = []
        for tx in res.get('txs', []):
            as_json = json.loads(tx['as_json'])
            fee = as_json.get('rct_signatures', {}).get('txnFee')
            txs.append(Transaction(
                hash=tx['tx_hash'],
                fee=from_atomic(fee) if fee else None,
                height=None if tx['in_pool'] else tx['block_height'],
                timestamp=datetime.fromtimestamp(
                    tx['block_timestamp']) if 'block_timestamp' in tx else None,
                blob=binascii.unhexlify(tx['as_hex']),
                json=as_json))
        return txs 
开发者ID:monero-ecosystem,项目名称:monero-python,代码行数:21,代码来源:jsonrpc.py

示例12: _paymentdict

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromtimestamp [as 别名]
def _paymentdict(self, data):
        pid = data.get('payment_id', None)
        laddr = data.get('address', None)
        if laddr:
            laddr = address(laddr)
        result = {
            'payment_id': None if pid is None else PaymentID(pid),
            'amount': from_atomic(data['amount']),
            'timestamp': datetime.fromtimestamp(data['timestamp']) if 'timestamp' in data else None,
            'note': data.get('note', None),
            'transaction': self._tx(data),
            'local_address': laddr,
        }
        if 'destinations' in data:
            result['destinations'] = [
                (address(x['address']), from_atomic(x['amount']))
                for x in data.get('destinations')
            ]
        return result 
开发者ID:monero-ecosystem,项目名称:monero-python,代码行数:21,代码来源:jsonrpc.py

示例13: scheduled_times

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromtimestamp [as 别名]
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
        """Returns the times when this search is scheduled to run.

        By default this method returns the times in the next hour. For different
        time ranges, set *earliest_time* and *latest_time*. For example,
        for all times in the last day use "earliest_time=-1d" and
        "latest_time=now".

        :param earliest_time: The earliest time.
        :type earliest_time: ``string``
        :param latest_time: The latest time.
        :type latest_time: ``string``

        :return: The list of search times.
        """
        response = self.get("scheduled_times",
                            earliest_time=earliest_time,
                            latest_time=latest_time)
        data = self._load_atom_entry(response)
        rec = _parse_atom_entry(data)
        times = [datetime.fromtimestamp(int(t))
                 for t in rec.content.scheduled_times]
        return times 
开发者ID:remg427,项目名称:misp42splunk,代码行数:25,代码来源:client.py

示例14: _sendStartStatus

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromtimestamp [as 别名]
def _sendStartStatus(self, builderName, build):
        """
        Send start status to GitHub.
        """
        status = yield self._getGitHubRepoProperties(build)
        if not status:
            defer.returnValue(None)

        startTime, _ = build.getTimes()

        description = yield build.render(self._startDescription)

        status.update({
            'state': 'pending',
            'description': description,
            'builderName': builderName,
            'startDateTime': datetime.fromtimestamp(startTime).isoformat(' '),
            'endDateTime': 'In progress',
            'duration': 'In progress',
        })
        result = yield self._sendGitHubStatus(status)
        defer.returnValue(result) 
开发者ID:llvm,项目名称:llvm-zorg,代码行数:24,代码来源:github.py

示例15: _parse_aircraft_data

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromtimestamp [as 别名]
def _parse_aircraft_data(self, a, time):
        alt = a.get('Alt', 0)
        dist = -1
        az = 0
        el = 0
        if 'Lat' in a and 'Long' in a:
            rec_pos = (receiver_latitude, receiver_longitude)
            ac_pos = (a['Lat'], a['Long'])
            dist = geomath.distance(rec_pos, ac_pos)
            az = geomath.bearing(rec_pos, ac_pos)
            el = math.degrees(math.atan(alt / (dist * 5280)))
        speed = 0
        if 'Spd' in a:
            speed = geomath.knot2mph(a['Spd'])
        if 'PosTime' in a:
            last_seen_time = datetime.fromtimestamp(a['PosTime'] / 1000.0)
            seen = (time - last_seen_time).total_seconds()
        else:
            seen = 0
        ac_data = AirCraftData(
            a.get('Icao', None).upper(),
            a.get('Sqk', None),
            a.get('Call', None),
            a.get('Reg', None),
            a.get('Lat', None),
            a.get('Long', None),
            alt,
            a.get('Vsi', 0),
            a.get('Trak', None),
            speed,
            a.get('CMsgs', None),
            seen,
            a.get('Mlat', False),
            None,  # NUCP
            None,  # Seen pos
            10.0 * math.log10(a.get('Sig', 0) / 255.0 + 1e-5),
            dist,
            az,
            el,
            time)
        return ac_data 
开发者ID:kevinabrandon,项目名称:AboveTustin,代码行数:43,代码来源:flightdata.py


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