Python datetime.datetime.timestamp() Examples

The following are 30 code examples of datetime.datetime.timestamp(). 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: test_history.py    From Clash-Royale-Clan-Tools with GNU General Public License v3.0 6 votes vote down vote up
def test_get_member_history_role_change():
    date = datetime(2019, 2, 12, 7, 32, 1, 0)
    timestamp = datetime.timestamp(date)
    h = history.get_member_history(__fake_members__, date, __fake_history__, None)

    members = h['members']

    assert h['last_update'] == timestamp
    assert members[__fake_members__[1].tag]['status'] == 'present'
    assert members[__fake_members__[1].tag]['events'][1]['event'] == 'role change'
    assert members[__fake_members__[1].tag]['events'][1]['type'] == 'demotion'
    assert members[__fake_members__[1].tag]['events'][1]['role'] == __fake_members__[1].role
    assert members[__fake_members__[1].tag]['events'][1]['date'] == timestamp

    assert members[__fake_members__[2].tag]['status'] == 'present'
    assert members[__fake_members__[2].tag]['events'][1]['event'] == 'role change'
    assert members[__fake_members__[2].tag]['events'][1]['type'] == 'promotion'
    assert members[__fake_members__[2].tag]['events'][1]['role'] == __fake_members__[2].role
    assert members[__fake_members__[2].tag]['events'][1]['date'] == timestamp 
Example #2
Source File: dataset.py    From satpy with GNU General Public License v3.0 6 votes vote down vote up
def average_datetimes(dt_list):
    """Average a series of datetime objects.

    .. note::

        This function assumes all datetime objects are naive and in the same
        time zone (UTC).

    Args:
        dt_list (iterable): Datetime objects to average

    Returns: Average datetime as a datetime object

    """
    total = [datetime.timestamp(dt) for dt in dt_list]
    return datetime.fromtimestamp(sum(total) / len(total)) 
Example #3
Source File: test_unary_ops.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_timestamp(self):
        # GH#17329
        # tz-naive --> treat it as if it were UTC for purposes of timestamp()
        ts = Timestamp.now()
        uts = ts.replace(tzinfo=utc)
        assert ts.timestamp() == uts.timestamp()

        tsc = Timestamp('2014-10-11 11:00:01.12345678', tz='US/Central')
        utsc = tsc.tz_convert('UTC')

        # utsc is a different representation of the same time
        assert tsc.timestamp() == utsc.timestamp()

        if PY3:
            # datetime.timestamp() converts in the local timezone
            with tm.set_timezone('UTC'):
                # should agree with datetime.timestamp method
                dt = ts.to_pydatetime()
                assert dt.timestamp() == ts.timestamp() 
Example #4
Source File: lorawangtw.py    From empower-runtime with Apache License 2.0 6 votes vote down vote up
def to_dict(self):
        """Return a JSON-serializable dictionary representing the PNFDev."""
        if not self.last_seen:
            self.last_seen = datetime.now()
        date = datetime.timestamp(self.last_seen)

        return {
            'name': self.name,
            'lgtw_euid': self.lgtw_euid.id6,
            'desc': self.desc,
            'state': self.state.value,
            'owner': str(self.owner),
            'lgtw_version': self.lgtw_version,
            'lgtw_config': self.lgtw_config,
            'last_seen': self.last_seen,
            'last_seen_ts': date,
            'ipaddr': self.ipaddr
            } 
Example #5
Source File: trading.py    From cryptotrader with MIT License 6 votes vote down vote up
def crypto(self, values):
        try:
            # assert isinstance(values, dict), "Crypto value must be a dictionary containing the currencies balance."
            try:
                timestamp = values['timestamp']
            except KeyError:
                timestamp = self.timestamp
            for symbol, value in values.items():
                if symbol not in [self._fiat, 'timestamp']:
                    self.portfolio_df.at[timestamp, symbol] = convert_to.decimal(value)

        except TypeError:
            raise AssertionError("Crypto value must be a dictionary containing the currencies balance.")

        except Exception as e:
            Logger.error(TradingEnvironment.crypto, self.parse_error(e))
            raise e 
Example #6
Source File: queue.py    From mlq with MIT License 6 votes vote down vote up
def post(self, msg, callback=None, functions=None):
        msg_id = str(self._redis.incr(self.id_key))
        timestamp = dt.timestamp(dt.utcnow())
        logging.info('Posting message with id {} to {} at {}'.format(msg_id, self.q_name, timestamp))
        pipeline = self._redis.pipeline()
        pipeline.rpush(self.jobs_refs_q, msg_id)
        job = {
            'id': msg_id,
            'timestamp': timestamp,
            'worker': None,
            'processing_started': None,
            'processing_finished': None,
            'progress': None,
            'short_result': None,
            'result': None,
            'callback': callback,
            'retries': 0,
            'functions': functions, # Which function names should be called
            'msg': msg
        }
        job = msgpack.packb(job, use_bin_type=False)
        pipeline.lpush(self.q_name, job)
        pipeline.set(self.job_status_stem + msg_id, job)
        pipeline.execute()
        return msg_id 
Example #7
Source File: test_unary_ops.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_timestamp(self):
        # GH#17329
        # tz-naive --> treat it as if it were UTC for purposes of timestamp()
        ts = Timestamp.now()
        uts = ts.replace(tzinfo=utc)
        assert ts.timestamp() == uts.timestamp()

        tsc = Timestamp('2014-10-11 11:00:01.12345678', tz='US/Central')
        utsc = tsc.tz_convert('UTC')

        # utsc is a different representation of the same time
        assert tsc.timestamp() == utsc.timestamp()

        if PY3:
            # datetime.timestamp() converts in the local timezone
            with tm.set_timezone('UTC'):
                # should agree with datetime.timestamp method
                dt = ts.to_pydatetime()
                assert dt.timestamp() == ts.timestamp() 
Example #8
Source File: tasks.py    From arches with GNU Affero General Public License v3.0 6 votes vote down vote up
def delete_file():
    from arches.app.models.system_settings import settings

    settings.update_from_db()

    logger = logging.getLogger(__name__)
    now = datetime.timestamp(datetime.now())
    file_list = []
    range = datetime.now() - timedelta(seconds=settings.CELERY_SEARCH_EXPORT_EXPIRES)
    exports = models.SearchExportHistory.objects.filter(exporttime__lt=range).exclude(downloadfile="")
    for export in exports:
        file_list.append(export.downloadfile.url)
        export.downloadfile.delete()
    deleted_message = _("files_deleted")
    logger.warning(f"{len(file_list)} {deleted_message}")
    return f"{len(file_list)} {deleted_message}" 
Example #9
Source File: test_history.py    From Clash-Royale-Clan-Tools with GNU General Public License v3.0 6 votes vote down vote up
def test_get_member_history_quit_and_rejoin():
    date = datetime(2019, 2, 12, 7, 32, 1, 0)
    date2 = datetime(2019, 2, 12, 7, 32, 2, 0)
    timestamp = datetime.timestamp(date)
    timestamp2 = datetime.timestamp(date2)
    members = __fake_members__.copy()
    del members[2]

    h = history.get_member_history(members, date, __fake_history__, None)
    h2 = history.get_member_history(__fake_members__, date2, h, None)

    h_member = h['members'][__fake_members__[2].tag]
    h2_member = h2['members'][__fake_members__[2].tag]

    assert h_member['status'] == 'absent'
    assert h_member['events'][1]['event'] == 'quit'
    assert h_member['events'][1]['type'] == 'left'
    assert h_member['events'][1]['date'] == timestamp
    assert h2_member['status'] == 'present'
    assert h2_member['events'][1]['event'] == 'quit'
    assert h2_member['events'][1]['type'] == 'left'
    assert h2_member['events'][1]['date'] == timestamp
    assert h2_member['events'][2]['event'] == 'join'
    assert h2_member['events'][2]['type'] == 're-join'
    assert h2_member['events'][2]['date'] == timestamp2 
Example #10
Source File: history.py    From Clash-Royale-Clan-Tools with GNU General Public License v3.0 6 votes vote down vote up
def process_missing_members(historical_mambers, member_tags, timestamp):
    """ Look for missing members. If they're missing, they quit """
    missing_members = copy.deepcopy(historical_mambers)

    for tag, missing_member in missing_members.items():
        if tag not in member_tags:
            if missing_member['status'] != 'absent':
                missing_member['events'].append({
                    'event': 'quit',
                    'type':  'left',
                    'role':  missing_member['role'],
                    'date':  timestamp
                })
                missing_member['status'] = 'absent'
            if 'name' not in missing_member:
                missing_member['name'] = NAME_UNKNOWN

    return missing_members 
Example #11
Source File: trading.py    From cryptotrader with MIT License 6 votes vote down vote up
def reset(self):
        self.obs_df = pd.DataFrame()
        self.portfolio_df = pd.DataFrame()

        # self.set_observation_space()
        # self.set_action_space()

        self.balance = self.init_balance = self.get_balance()

        # for symbol in self.symbols:
        #     self.tax[symbol] = convert_to.decimal(self.get_fee(symbol))

        obs = self.get_observation(True)

        self.action_df = pd.DataFrame([list(self.calc_portfolio_vector()) + [False]],
                                      columns=list(self.symbols) + ['online'],
                                      index=[self.timestamp])

        self.portval = {'portval': self.calc_total_portval(),
                        'timestamp': self.portfolio_df.index[-1]}

        return obs.astype(np.float64) 
Example #12
Source File: trading.py    From cryptotrader with MIT License 6 votes vote down vote up
def calc_total_portval(self, ticker=None, timestamp=None):
        """
        Calculate total portfolio value given last pair prices
        :param timestamp: For compatibility only
        :return: Decimal: Total portfolio value in fiat units
        """
        portval = dec_zero
        balance = self.get_balance()
        if not ticker:
            ticker = self.tapi.returnTicker()
        for pair in self.pairs:
            portval = balance[pair.split('_')[1]].fma(convert_to.decimal(ticker[pair]['last']),
                                                      portval)

        portval = dec_con.add(portval, balance[self._fiat])

        return dec_con.create_decimal(portval) 
Example #13
Source File: trading.py    From cryptotrader with MIT License 6 votes vote down vote up
def reset(self):
        self.obs_df = pd.DataFrame()
        self.portfolio_df = pd.DataFrame()

        # self.set_observation_space()
        # self.set_action_space()

        self.balance = self.init_balance = self.get_balance()

        # for symbol in self.symbols:
        #     self.tax[symbol] = convert_to.decimal(self.get_fee(symbol))

        obs = self.get_observation(True)

        self.action_df = pd.DataFrame([list(self.calc_portfolio_vector()) + [False]],
                                      columns=list(self.symbols) + ['online'],
                                      index=[self.timestamp])

        self.portval = {'portval': self.calc_total_portval(),
                        'timestamp': self.portfolio_df.index[-1]}

        return obs.astype(np.float64) 
Example #14
Source File: history.py    From Clash-Royale-Clan-Tools with GNU General Public License v3.0 6 votes vote down vote up
def validate_history(old_history, timestamp):
    """ Returns True if and only if the history object is
    validly formatted """
    if type(old_history) == dict \
        and 'last_update' in old_history \
        and 'members' in old_history \
        and type(old_history['members']) == dict:
        history = copy.deepcopy(old_history)

        history['last_update'] = timestamp
        if 'history_start' not in history:
            history['history_start'] = find_oldest_date(history['members'])

        return history, False
    else:
        history = {
            'history_start': timestamp,
            'last_update': timestamp,
            'members': {}
        }
        # if history is new, we want all members to have a join
        # date of 0, implying that they've joined before recorded
        # history
        return history, True 
Example #15
Source File: warparticipation.py    From Clash-Royale-Clan-Tools with GNU General Public License v3.0 6 votes vote down vote up
def _get_war_date(war):
    """ returns the datetime this war was created. If it's an ongoing
    war, calculate based on the dates given when the war started.
    If it's a previous war fromt he warlog, we retrieve the creation
    date. What's returned is a timestamp. """
    war_date_raw = 0

    if hasattr(war, 'state') :
        if war.state == 'warDay':
            war_date_raw = datetime.strptime(war.war_end_time.split('.')[0], '%Y%m%dT%H%M%S')
            war_date_raw -= timedelta(days=2)
        elif war.state == 'collectionDay':
            war_date_raw = datetime.strptime(war.collection_end_time.split('.')[0], '%Y%m%dT%H%M%S')
            war_date_raw -= timedelta(days=1)
    else:
        war_date_raw = datetime.strptime(war.created_date.split('.')[0], '%Y%m%dT%H%M%S')
        war_date_raw -= timedelta(days=1)

    return datetime.timestamp(war_date_raw) 
Example #16
Source File: __init__.py    From platypush with MIT License 6 votes vote down vote up
def _get_avg_fps(self, frames_dir):
        files = self._get_stored_frames_files(frames_dir)
        frame_time_diff = 0.0
        n_frames = 0

        for i in range(1, len(files)):
            m1 = re.search(self._frame_filename_regex, files[i - 1])
            m2 = re.search(self._frame_filename_regex, files[i])

            if not m1 or not m2:
                continue

            t1 = datetime.timestamp(datetime(*map(int, m1.groups())))
            t2 = datetime.timestamp(datetime(*map(int, m2.groups())))
            frame_time_diff += (t2 - t1)
            n_frames += 1

        return n_frames / frame_time_diff if n_frames and frame_time_diff else 0 
Example #17
Source File: workflow.py    From dingtalk-python with Apache License 2.0 6 votes vote down vote up
def get_bpms_instance_list(access_token, process_code, start_time, end_time=None, size=10, cursor=0):
    """
    企业可以根据审批流的唯一标识,分页获取该审批流对应的审批实例。只能取到权限范围内的相关部门的审批实例
    :param access_token:
    :param process_code:
    :param start_time:
    :param end_time:
    :param size:
    :param cursor:
    :return:
    """
    start_time = datetime.timestamp(start_time)
    start_time = int(round(start_time * 1000))
    if end_time:
        end_time = datetime.timestamp(end_time)
        end_time = int(round(end_time * 1000))
    args = locals()
    payload = {}
    for key in ('process_code', 'start_time', 'end_time', 'size', 'cursor'):
        if args.get(key, no_value) is not None:
            payload.update({key: args[key]})
    resp = call_dingtalk_webapi(access_token, 'dingtalk.smartwork.bpms.processinstance.list', 'GET', **payload)
    return resp 
Example #18
Source File: foundation.py    From dingtalk-python with Apache License 2.0 6 votes vote down vote up
def get_request_url(access_token, method=None, format_='json', v='2.0', simplify='false', partner_id=None, url=None):
    """
    通用的获取请求地址的方法
    :param access_token:
    :param method:
    :param format_:
    :param v:
    :param simplify:
    :param partner_id:
    :param url:
    :return:
    """
    from datetime import datetime
    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    base_url = url or DING_METHODS_URL
    request_url = '{0}?method={1}&session={2}&timestamp={3}&format={4}&v={5}'.format(base_url, method, access_token,
                                                                                     timestamp, format_, v)
    if format_ == 'json':
        request_url = '{0}&simplify={1}'.format(request_url, simplify)
    if partner_id:
        request_url = '{0}&partner_id={1}'.format(request_url, partner_id)
    return request_url 
Example #19
Source File: test_unary_ops.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def test_timestamp(self):
        # GH#17329
        # tz-naive --> treat it as if it were UTC for purposes of timestamp()
        ts = Timestamp.now()
        uts = ts.replace(tzinfo=utc)
        assert ts.timestamp() == uts.timestamp()

        tsc = Timestamp('2014-10-11 11:00:01.12345678', tz='US/Central')
        utsc = tsc.tz_convert('UTC')

        # utsc is a different representation of the same time
        assert tsc.timestamp() == utsc.timestamp()

        if PY3:
            # datetime.timestamp() converts in the local timezone
            with tm.set_timezone('UTC'):
                # should agree with datetime.timestamp method
                dt = ts.to_pydatetime()
                assert dt.timestamp() == ts.timestamp() 
Example #20
Source File: graphene.py    From cloud-volume with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def to_unix_time(timestamp):
  """
  Accepts integer UNIX timestamps, ISO 8601 datetime strings,
  and Python datetime objects and returns them as the equivalent
  UNIX timestamp or None if timestamp is None.
  """
  if isinstance(timestamp, str):
    timestamp = dateutil.parser.parse(timestamp) # returns datetime
  if isinstance(timestamp, datetime): # NB. do not change to elif
    timestamp = datetime.timestamp(timestamp)

  if not isinstance(timestamp, int) and timestamp is not None:
    raise ValueError("Not able to convert {} to UNIX time.".format(timestamp))

  return timestamp 
Example #21
Source File: test_history.py    From Clash-Royale-Clan-Tools with GNU General Public License v3.0 5 votes vote down vote up
def test_get_member_history_unchanged():
    """ Getting history twice. Nothing should be changed except the
    timestamp """
    date = datetime(2019, 2, 12, 7, 32, 1, 0)
    date2 = datetime(2019, 2, 12, 7, 32, 2, 0)
    timestamp = datetime.timestamp(date)
    timestamp2 = datetime.timestamp(date2)

    h = history.get_member_history(__fake_members__, date, None, None)
    h2 = history.get_member_history(__fake_members__, date2, h, None)

    assert h['last_update'] == timestamp
    assert h2['last_update'] == timestamp2
    assert h['members'] == h2['members'] 
Example #22
Source File: history.py    From Clash-Royale-Clan-Tools with GNU General Public License v3.0 5 votes vote down vote up
def create_new_member(member, timestamp, new_clan):
    return cleanup_member_history(member, {}, timestamp, new_clan) 
Example #23
Source File: logs.py    From polyaxon with Apache License 2.0 5 votes vote down vote up
def upload_logs(run_uuid: str, logs: List[V1Log]):
    if not settings.AGENT_CONFIG.artifacts_store:
        raise HTTPException(
            detail="Run's logs was not collected, resource was not found.",
            status_code=status.HTTP_400_BAD_REQUEST,
        )
    for c_logs in V1Logs.chunk_logs(logs):
        last_file = datetime.timestamp(c_logs.logs[-1].timestamp)
        subpath = "{}/plxlogs/{}".format(run_uuid, last_file)
        await upload_data(subpath=subpath, data=c_logs.to_dict(dump=True)) 
Example #24
Source File: history.py    From Clash-Royale-Clan-Tools with GNU General Public License v3.0 5 votes vote down vote up
def cleanup_member_history(member, history, timestamp, new_clan=False):
    """ make sure member history entry has all the necessary fields.
    This is here to make upgrades smooth """
    now = timestamp
    if new_clan == True:
        now = 0
    if 'name' not in history or history['name'] == NAME_UNKNOWN:
        history['name'] = member.name
    if 'join_date' not in history:
        history['join_date'] = now
    if 'last_activity_date' not in history:
        history['last_activity_date'] = timestamp
    if 'last_donation_date' not in history:
        history['last_donation_date'] = timestamp
    if 'role' not in history:
        history['role'] = member.role
    if 'status' not in history:
        history['status'] = 'present'
    if 'donations' not in history:
        history['donations'] = member.donations
    if 'donations_last_week' not in history:
        history['donations_last_week'] = 0
    if 'events' not in history:
        history['events'] = [{
                                'event': 'join',
                                'type':  'new',
                                'role':  member.role,
                                'date':  now
                            }]
    return history 
Example #25
Source File: utils.py    From dwave-cloud-client with Apache License 2.0 5 votes vote down vote up
def datetime_to_timestamp(dt):
    """Convert timezone-aware `datetime` to POSIX timestamp and
    return seconds since UNIX epoch.

    Note: similar to `datetime.timestamp()` in Python 3.3+.
    """

    epoch = datetime.utcfromtimestamp(0).replace(tzinfo=UTC)
    return (dt - epoch).total_seconds() 
Example #26
Source File: utils.py    From dwave-cloud-client with Apache License 2.0 5 votes vote down vote up
def epochnow():
    """Returns now as UNIX timestamp.

    Invariant:
        epochnow() ~= datetime_to_timestamp(utcnow())

    """
    return time.time() 
Example #27
Source File: foundation.py    From dingtalk-python with Apache License 2.0 5 votes vote down vote up
def get_timestamp():
    """
    生成时间戳
    :return:
    """

    now = datetime.now()
    timestamp = datetime.timestamp(now)
    timestamp = int(round(timestamp))
    return timestamp 
Example #28
Source File: handler.py    From aws-syndicate with Apache License 2.0 5 votes vote down vote up
def current_timestamp():
    return int(datetime.timestamp(datetime.now())) 
Example #29
Source File: helpers.py    From mercure with GNU General Public License v3.0 5 votes vote down vote up
def to_hour_timestamp(datetime):
    """Get timestamp (without minutes and second)

    :param datetime: datetime object
    :return: timestamp
    """
    return int(datetime.timestamp() / 3600) * 3600 
Example #30
Source File: history.py    From Clash-Royale-Clan-Tools with GNU General Public License v3.0 5 votes vote down vote up
def member_rejoin(historical_member, member, timestamp):
    updated_member = copy.deepcopy(historical_member)
    updated_member['events'].append({
        'event': 'join',
        'type':  're-join',
        'role':  member.role,
        'date':  timestamp
    })
    updated_member['role'] = member.role
    updated_member['status'] = 'present'
    updated_member['last_activity_date'] = timestamp

    return updated_member