本文整理汇总了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}"
示例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()
示例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
示例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)
示例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)
示例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}×tamp={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
示例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
示例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
示例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)
示例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
示例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
示例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
示例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
示例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
}
示例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))