Python datetime.datetime.fromtimestamp() Examples

The following are 30 code examples of datetime.datetime.fromtimestamp(). 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 also want to check out all available functions/classes of the module datetime.datetime , or try the search function .
Example #1
Source File: __init__.py    From aegea with Apache License 2.0 9 votes vote down vote up
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)) 
Example #2
Source File: driver_utils.py    From toolium with Apache License 2.0 6 votes vote down vote up
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())) 
Example #3
Source File: getmetrics_sar.py    From InsightAgent with Apache License 2.0 6 votes vote down vote up
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')) 
Example #4
Source File: jsonrpc.py    From monero-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #5
Source File: jsonrpc.py    From monero-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #6
Source File: base.py    From django-anonymizer with MIT License 6 votes vote down vote up
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) 
Example #7
Source File: github.py    From llvm-zorg with Apache License 2.0 6 votes vote down vote up
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) 
Example #8
Source File: computer.py    From pyspectator with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #9
Source File: instapaper.py    From pyinstapaper with MIT License 6 votes vote down vote up
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,) 
Example #10
Source File: test_utils.py    From Zopkio with Apache License 2.0 6 votes vote down vote up
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) 
Example #11
Source File: trigger.py    From worker with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #12
Source File: attime.py    From worker with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #13
Source File: structures.py    From instaloader with MIT License 5 votes vote down vote up
def latest_media_local(self) -> datetime:
        """Timestamp when the last item of the story was created (local time zone)."""
        return datetime.fromtimestamp(self._node['latest_reel_media']) 
Example #14
Source File: structures.py    From instaloader with MIT License 5 votes vote down vote up
def last_seen_local(self) -> Optional[datetime]:
        """Timestamp when the story has last been watched or None (local time zone)."""
        if self._node['seen']:
            return datetime.fromtimestamp(self._node['seen'])
        return None 
Example #15
Source File: ledger_cmds.py    From libra-client with MIT License 5 votes vote down vote up
def execute(self, client, params, **kwargs):
        client = self.get_real_client(client, **kwargs)
        start_time = client.get_transaction(1).transaction.timestamp_usecs
        latest_time = client.get_metadata().timestamp
        start_time = datetime.fromtimestamp(start_time / 1000_000)
        latest_time = datetime.fromtimestamp(latest_time / 1000_000)
        json_print_in_cmd({
            "start_time": start_time.strftime("%Y-%m-%dT%H:%M:%S"),
            "latest_time": latest_time.strftime("%Y-%m-%dT%H:%M:%S")
        }, sort_keys=False) 
Example #16
Source File: structures.py    From instaloader with MIT License 5 votes vote down vote up
def expiring_local(self) -> datetime:
        """Timestamp when the StoryItem will get unavailable (local time zone)."""
        return datetime.fromtimestamp(self._node['expiring_at_timestamp']) 
Example #17
Source File: structures.py    From instaloader with MIT License 5 votes vote down vote up
def date_local(self) -> datetime:
        """Timestamp when the StoryItem was created (local time zone)."""
        return datetime.fromtimestamp(self._node['taken_at_timestamp']) 
Example #18
Source File: test_storage_cassandra.py    From dino with Apache License 2.0 5 votes vote down vote up
def act_message(self):
        data = self.activity_for_message()
        data['id'] = StorageCassandraTest.MESSAGE_ID
        data['target']['objectType'] = 'group'
        data['published'] = datetime.fromtimestamp(time.time()).strftime('%Y-%m-%dT%H:%M:%SZ')
        return parse(data) 
Example #19
Source File: jsonrpc.py    From monero-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _tx(self, data):
        return Transaction(**{
            'hash': data.get('txid', data.get('tx_hash')),
            'fee': from_atomic(data['fee']) if 'fee' in data else None,
            'key': data.get('key'),
            'height': data.get('height', data.get('block_height')) or None,
            'timestamp': datetime.fromtimestamp(data['timestamp']) if 'timestamp' in data else None,
            'blob': binascii.unhexlify(data.get('blob', '')),
            'confirmations': data.get('confirmations', None)
        }) 
Example #20
Source File: __init__.py    From dino with Apache License 2.0 5 votes vote down vote up
def is_banned(user_id: str, room_id: str) -> (bool, Union[str, None]):
    bans = environ.env.db.get_user_ban_status(room_id, user_id)

    global_time = bans['global']
    channel_time = bans['channel']
    room_time = bans['room']
    now = datetime.utcnow()

    if global_time != '':
        end = datetime.fromtimestamp(int(global_time))
        seconds = str((end - now).seconds)
        logger.debug('user %s is banned globally for another %s seconds' %
                     (user_id, str((end - now).seconds)))
        return True, {'scope': 'global', 'seconds': seconds, 'id': ''}

    if channel_time != '':
        end = datetime.fromtimestamp(int(channel_time))
        seconds = str((end - now).seconds)
        channel_id = get_channel_for_room(room_id)
        logger.debug('user %s is banned in channel %s for another %s seconds' %
                     (user_id, channel_id, str((end - now).seconds)))
        return True, {'scope': 'channel', 'seconds': seconds, 'id': channel_id}

    if room_time != '':
        end = datetime.fromtimestamp(int(float(room_time)))
        seconds = str((end - now).seconds)
        logger.debug('user %s is banned in room %s for another %s seconds' %
                     (user_id, room_id, str((end - now).seconds)))
        return True, {'scope': 'room', 'seconds': seconds, 'id': room_id}

    return False, None 
Example #21
Source File: redis.py    From dino with Apache License 2.0 5 votes vote down vote up
def is_banned_from_channel(self, channel_id: str, user_id: str) -> (bool, Union[str, None]):
        ban = self.redis.hget(RedisKeys.banned_users_channel(channel_id), user_id)
        is_banned, time = self._is_banned(ban)
        if not is_banned:
            return False, None

        now = datetime.utcnow()
        end = datetime.fromtimestamp(float(time))
        if now > end:
            self.redis.hdel(RedisKeys.banned_users(), user_id)
            return False, None
        return True, time 
Example #22
Source File: jsonrpc.py    From monero-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def block(self, bhash=None, height=None):
        data = {}
        if bhash:
            data['hash'] = bhash
        if height:
            data['height'] = height
        res = self.raw_jsonrpc_request('get_block', data)
        if res['status'] == 'OK':
            bhdr = res['block_header']
            sub_json = json.loads(res['json'])
            data = {
                'blob': res['blob'],
                'hash': bhdr['hash'],
                'height': bhdr['height'],
                'timestamp': datetime.fromtimestamp(bhdr['timestamp']),
                'version': (bhdr['major_version'], bhdr['minor_version']),
                'difficulty': bhdr['difficulty'],
                'nonce': bhdr['nonce'],
                'orphan': bhdr['orphan_status'],
                'prev_hash': bhdr['prev_hash'],
                'reward': from_atomic(bhdr['reward']),
                'transactions': self.transactions(
                    [bhdr['miner_tx_hash']] + sub_json['tx_hashes']),
            }
            return Block(**data)
        raise exceptions.BackendException(res['status']) 
Example #23
Source File: jsonrpc.py    From monero-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def mempool(self):
        res = self.raw_request('/get_transaction_pool', {})
        txs = []
        for tx in res.get('transactions', []):
            txs.append(Transaction(
                hash=tx['id_hash'],
                fee=from_atomic(tx['fee']),
                timestamp=datetime.fromtimestamp(tx['receive_time']),
                blob=binascii.unhexlify(tx['tx_blob']),
                json=json.loads(tx['tx_json']),
                confirmations=0))
        return txs 
Example #24
Source File: client.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 
Example #25
Source File: libra_shell.py    From libra-client with MIT License 5 votes vote down vote up
def run_shell(args):  # noqa: C901
    grpc_client = Client.new(args.url, args.faucet_account_file)
    try:
        info = grpc_client.get_latest_ledger_info()
        time = datetime.fromtimestamp(info.timestamp / 1000_000)
        ledger_info_str = f"latest version = {info.version}, timestamp = {time}"
    except Exception as err:
        report_error(f"Not able to connect to validator at {args.url}", err, args.verbose)
        return
    client_proxy = ClientProxy(grpc_client, args)
    client_info = f"Connected to validator at: {grpc_client.url}, {ledger_info_str}"
    print(client_info)
    (commands, alias_to_cmd) = get_commands(grpc_client.faucet_account is not None)
    while True:
        prompt = "libra% "
        if support_color():
            prompt = f'\033[91m{prompt}\033[0m'
        try:
            line = input(prompt)
        except EOFError:
            sys.exit(0)
        params = parse_cmd(line)
        if len(params) == 0:
            continue
        cmd = alias_to_cmd.get(params[0])
        if cmd is not None:
            if args.verbose:
                print(datetime.now().strftime("%Y-%m-%d,%H:%M:%S"))
            cmd.execute(client_proxy, params, proxy=True)
        else:
            if params[0] == "quit" or params[0] == "q!":
                break
            elif params[0] == "help" or params[0] == "h":
                print_help(client_info, commands)
            else:
                print(f"Unknown command: {params[0]}") 
Example #26
Source File: helper.py    From hsds with Apache License 2.0 5 votes vote down vote up
def getTestDomainName(name):
    now = time.time()
    dt = datetime.fromtimestamp(now, pytz.utc)
    domain = "{:04d}{:02d}{:02d}T{:02d}{:02d}{:02d}_{:06d}Z".format(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond)  
    domain += '.' 
    domain += name.lower()
    domain += '.'
    domain += config.get('user_name')
    domain += '.home'
    return domain 
Example #27
Source File: helper.py    From hsds with Apache License 2.0 5 votes vote down vote up
def getTestDomainName(name):
    now = time.time()
    dt = datetime.fromtimestamp(now, pytz.utc)
    domain = "/home/"
    domain += config.get('user_name')
    domain += '/'
    domain += 'hsds_test'
    domain += '/'
    domain += name.lower()
    domain += '/'
    domain += "{:04d}{:02d}{:02d}T{:02d}{:02d}{:02d}_{:06d}Z".format(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond)
    return domain 
Example #28
Source File: timeUtil.py    From hsds with Apache License 2.0 5 votes vote down vote up
def unixTimeToUTC(timestamp):
    """Convert unix timestamp (seconds since Jan 1, 1970, to ISO-8601
    compatible UTC time string.

    """
    utc = pytz.utc
    dtTime = datetime.fromtimestamp(timestamp, utc)
    iso_str = dtTime.isoformat()
    # isoformat returns a string like this:
    # '2014-10-30T04:25:21+00:00'
    # strip off the '+00:00' and replace
    # with 'Z' (both are ISO-8601 compatible)
    npos = iso_str.rfind('+')
    iso_z = iso_str[:npos] + 'Z'
    return iso_z 
Example #29
Source File: tcx_builder.py    From peloton-to-garmin with GNU General Public License v3.0 5 votes vote down vote up
def getTimeStamp(timeInSeconds):
    timestamp = datetime.fromtimestamp(timeInSeconds, timezone.utc)
    iso = timestamp.isoformat()
    return iso.replace("+00:00", ".000Z") 
Example #30
Source File: utils.py    From NanoPlot with GNU General Public License v3.0 5 votes vote down vote up
def init_logs(args, tool="NanoPlot"):
    """Initiate log file and log arguments."""
    start_time = dt.fromtimestamp(time()).strftime('%Y%m%d_%H%M')
    logname = os.path.join(args.outdir, args.prefix + tool + "_" + start_time + ".log")
    handlers = [logging.FileHandler(logname)]
    if args.verbose:
        handlers.append(logging.StreamHandler())
    logging.basicConfig(
        format='%(asctime)s %(message)s',
        handlers=handlers,
        level=logging.INFO)
    logging.info('{} {} started with arguments {}'.format(tool, __version__, args))
    logging.info('Python version is: {}'.format(sys.version.replace('\n', ' ')))
    return logname