You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将uint256时间戳转为hh:mm:ss格式及int256转为浮点数

解决方案

1. uint256时间戳转hh:mm:ss格式

你拿到的uint256时间戳是Unix秒级时间戳,转换为可读时分秒的核心是把数值转为日期时间对象,再格式化输出。以下是两种常用语言的实现:

JavaScript

// 示例时间戳
const timestamp = 1678871792;
// 转为Date对象(需乘1000转毫秒)
const date = new Date(timestamp * 1000);
// 格式化为24小时制hh:mm:ss
const timeStr = date.toLocaleTimeString('en-US', {
  hour12: false,
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit'
});
console.log(timeStr); // 输出对应时区的时分秒(如UTC+8下示例为10:36:32)

Python

from datetime import datetime

timestamp = 1678871792
# 转为本地时区datetime对象,要UTC的话用utcfromtimestamp
dt = datetime.fromtimestamp(timestamp)
# 格式化hh:mm:ss
time_str = dt.strftime('%H:%M:%S')
print(time_str)

注意:时间戳默认是UTC时间,格式化时会根据本地时区转换,若需UTC时间需调整代码。

2. int256价格数据转浮点数格式

DeFi合约里的价格整数是实际浮点数乘以精度倍数后存储的,你提供的示例对应的精度是10^8(即8位小数),转换公式为:实际价格 = 合约返回整数 / 10^decimals。

对示例的计算:

  • lockPrice 27554820000 → 27554820000 / 100000000 = 275.5482
  • closePrice 27550780000 → 27550780000 / 100000000 = 275.5078

代码实现:

JavaScript

const lockPrice = 27554820000;
const decimals = 8;
const actualPrice = lockPrice / (10 ** decimals);
console.log(actualPrice.toFixed(4)); // 保留4位小数输出275.5482

Python

lock_price = 27554820000
decimals = 8
actual_price = lock_price / (10 ** decimals)
print(f"{actual_price:.4f}") # 输出275.5482

如果不确定精度值,可通过合约的decimals读取方法确认,或对比官网显示的浮点数反向计算。


内容的提问来源于stack exchange,提问作者994kk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 09:25:30