Pharos
Global

_D - 时间戳转换

将时间戳转换为可读的时间字符串。

语法

python
# 获取当前时间字符串
time_str = _D()

# 将时间戳转换为时间字符串
time_str = _D(timestamp)

# 使用自定义格式
time_str = _D(timestamp, fmt)

参数

参数名类型必选默认值说明
timestampnumber/datetimeNone秒级时间戳或 datetime 对象。• 不传参数时返回当前时间• 注意:Python中使用秒级时间戳,而非毫秒
fmtstring'%Y-%m-%d %H:%M:%S'时间格式化字符串

返回值

返回格式化后的时间字符串(str)。

格式化占位符

占位符说明示例
%Y4位年份2019
%m2位月份11
%d2位日期29
%H24小时制小时10
%M分钟13
%S26
%I12小时制小时10
%pAM/PMAM
%a星期简称Mon
%A星期全称Monday
%b月份简称Nov
%B月份全称November

示例

示例1: 获取当前时间

python
# 获取当前时间(默认格式)
current = _D()
Log(f"当前时间: {current}")  # 输出: 2019-11-29 10:13:26

示例2: 转换时间戳

python
import time

# 获取当前秒级时间戳
timestamp = int(time.time())

# 转换为可读格式
time_str = _D(timestamp)
Log(f"时间: {time_str}")  # 输出: 2019-11-29 10:13:26

示例3: 自定义格式

python
import time

timestamp = int(time.time())

# 日期格式
date_str = _D(timestamp, '%Y-%m-%d')
Log(date_str)  # 输出: 2019-11-29

# 时间格式
time_str = _D(timestamp, '%H:%M:%S')
Log(time_str)  # 输出: 10:13:26

# 自定义分隔符
custom = _D(timestamp, '%Y--%m--%d')
Log(custom)  # 输出: 2019--11--29

# 完整格式
full = _D(timestamp, '%Y年%m月%d日 %H时%M分%S秒')
Log(full)  # 输出: 2019年11月29日 10时13分26秒

示例4: 处理订单时间

python
orders = exchange.GetHistoryOrders()

for order in orders:
    # 订单时间是毫秒级时间戳,需要转换为秒
    order_time = _D(order['Time'] / 1000)
    Log(f"订单 {order['Id']} 创建于: {order_time}")

示例5: 日志时间格式化

python
import time

# 记录操作时间
start_time = time.time()

# ... 执行一些操作 ...

end_time = time.time()
elapsed = end_time - start_time

Log(f"操作开始: {_D(start_time)}")
Log(f"操作结束: {_D(end_time)}")
Log(f"耗时: {elapsed:.2f} 秒")

示例6: 结合 datetime 对象

python
from datetime import datetime, timedelta

# 当前时间
now = datetime.now()
Log(_D(now))  # 输出: 2019-11-29 10:13:26

# 昨天
yesterday = now - timedelta(days=1)
Log(_D(yesterday))  # 输出: 2019-11-28 10:13:26

# 一小时前
one_hour_ago = now - timedelta(hours=1)
Log(_D(one_hour_ago))  # 输出: 2019-11-29 09:13:26

注意事项

  1. 时间戳精度:Python 使用秒级时间戳,而交易所 API 通常返回毫秒级时间戳,需要除以 1000

  2. 时区:默认使用本地时区,不会进行时区转换

  3. 格式化字符串:支持所有 Python strftime 的格式化占位符

  4. None 参数:不传参数时返回当前时间,等同于 _D(time.time())

相关 API

  • Unix - 获取秒级时间戳
  • UnixNano - 获取纳秒级时间戳
  • Sleep - 休眠指定毫秒数