當前位置: 首頁>>代碼示例>>Python>>正文


Python datetime.timestamp方法代碼示例

本文整理匯總了Python中datetime.datetime.timestamp方法的典型用法代碼示例。如果您正苦於以下問題:Python datetime.timestamp方法的具體用法?Python datetime.timestamp怎麽用?Python datetime.timestamp使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在datetime.datetime的用法示例。


在下文中一共展示了datetime.timestamp方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: delete_file

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timestamp [as 別名]
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}" 
開發者ID:archesproject,項目名稱:arches,代碼行數:18,代碼來源:tasks.py

示例2: test_timestamp

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timestamp [as 別名]
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() 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:21,代碼來源:test_unary_ops.py

示例3: crypto

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timestamp [as 別名]
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 
開發者ID:naripok,項目名稱:cryptotrader,代碼行數:19,代碼來源:trading.py

示例4: reset

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timestamp [as 別名]
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) 
開發者ID:naripok,項目名稱:cryptotrader,代碼行數:24,代碼來源:trading.py

示例5: calc_total_portval

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timestamp [as 別名]
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) 
開發者ID:naripok,項目名稱:cryptotrader,代碼行數:19,代碼來源:trading.py

示例6: get_request_url

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timestamp [as 別名]
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 
開發者ID:blackmatrix7,項目名稱:dingtalk-python,代碼行數:24,代碼來源:foundation.py

示例7: get_bpms_instance_list

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timestamp [as 別名]
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 
開發者ID:blackmatrix7,項目名稱:dingtalk-python,代碼行數:25,代碼來源:workflow.py

示例8: _get_avg_fps

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timestamp [as 別名]
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 
開發者ID:BlackLight,項目名稱:platypush,代碼行數:20,代碼來源:__init__.py

示例9: _get_war_date

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timestamp [as 別名]
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) 
開發者ID:AaronTraas,項目名稱:Clash-Royale-Clan-Tools,代碼行數:21,代碼來源:warparticipation.py

示例10: validate_history

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timestamp [as 別名]
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 
開發者ID:AaronTraas,項目名稱:Clash-Royale-Clan-Tools,代碼行數:26,代碼來源:history.py

示例11: process_missing_members

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timestamp [as 別名]
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 
開發者ID:AaronTraas,項目名稱:Clash-Royale-Clan-Tools,代碼行數:20,代碼來源:history.py

示例12: test_get_member_history_role_change

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timestamp [as 別名]
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 
開發者ID:AaronTraas,項目名稱:Clash-Royale-Clan-Tools,代碼行數:21,代碼來源:test_history.py

示例13: test_get_member_history_quit_and_rejoin

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timestamp [as 別名]
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 
開發者ID:AaronTraas,項目名稱:Clash-Royale-Clan-Tools,代碼行數:27,代碼來源:test_history.py

示例14: to_dict

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timestamp [as 別名]
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
            } 
開發者ID:5g-empower,項目名稱:empower-runtime,代碼行數:20,代碼來源:lorawangtw.py

示例15: average_datetimes

# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import timestamp [as 別名]
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)) 
開發者ID:pytroll,項目名稱:satpy,代碼行數:18,代碼來源:dataset.py


注:本文中的datetime.datetime.timestamp方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。