技能标识:timestamp-converter
Convert between Unix timestamps, ISO 8601 dates, and human-readable formats. Use when working with timestamps from APIs, logs, or databases that need conversion to local time, timezone adjustments, or format standardization. Supports batch conversion, timezone handling, and date arithmetic for developers working with temporal data.
在Unix时间戳、ISO日期和人类可读格式之间进行转换。
python
from datetime import datetime, timezone
def unixtodatetime(timestamp, tz=None):
将Unix时间戳转换为datetime对象
参数:
timestamp: Unix时间戳(秒或毫秒)
tz: 目标时区(默认:UTC)
# 自动检测秒或毫秒
if timestamp > 1e10:
timestamp = timestamp / 1000
dt = datetime.fromtimestamp(timestamp, tz=timezone.utc)
if tz:
dt = dt.astimezone(tz)
return dt
unixtodatetime(1704067200000) # 毫秒
python
def format_timestamp(timestamp, fmt=%Y-%m-%d %H:%M:%S):
将时间戳转换为自定义格式
dt = unixtodatetime(timestamp)
return dt.strftime(fmt)
python
from datetime import datetime
def parseiso8601(isostring):
解析ISO 8601字符串为datetime对象
# 处理各种ISO格式
isostring = isostring.replace(Z, +00:00)
return datetime.fromisoformat(iso_string)
def toiso8601(dt, includems=False):
将datetime对象转换为ISO 8601字符串
if include_ms:
return dt.isoformat()
return dt.strftime(%Y-%m-%dT%H:%M:%S%z)
python
from zoneinfo import ZoneInfo
def converttimezone(timestamp, fromtz=UTC, totz=America/NewYork):
在不同时区之间转换时间戳
dt = unixtodatetime(timestamp)
# 设置源时区
if from_tz != UTC:
dt = dt.replace(tzinfo=ZoneInfo(from_tz))
# 转换为目标时区
return dt.astimezone(ZoneInfo(to_tz))
python
from datetime import timedelta
def add_time(timestamp, days=0, hours=0, minutes=0):
为时间戳添加时间
dt = unixtodatetime(timestamp)
delta = timedelta(days=days, hours=hours, minutes=minutes)
return dt + delta
def time_diff(timestamp1, timestamp2):
计算两个时间戳之间的差值
dt1 = unixtodatetime(timestamp1)
dt2 = unixtodatetime(timestamp2)
diff = dt2 - dt1
return {
days: diff.days,
seconds: diff.seconds,
totalseconds: diff.totalseconds(),
hours: diff.total_seconds() / 3600
}
python
def batchconvert(timestamps, targetformat=%Y-%m-%d %H:%M:%S):
一次性转换多个时间戳
results = []
for ts in timestamps:
try:
formatted = formattimestamp(ts, targetformat)
results.append({timestamp: ts, formatted: formatted})
except Exception as e:
results.append({timestamp: ts, error: str(e)})
return results
| 格式 | 示例 | 使用场景 |
|---|---|---|
| Unix(秒) | 1704067200 | API、数据库 |
| Unix(毫秒) |
bash
pip install pytz
或使用Python 3.9+内置的zoneinfo:
python
from zoneinfo import ZoneInfo
以下为平台配置的接入选项,并非逐项实测通过。能否安装取决于客户端支持、技能来源和运行环境:
帮我安装 SkillHub 和 timestamp-converter-1776275362 技能
设置 SkillHub 为我的优先技能安装源,然后帮我安装 timestamp-converter-1776275362 技能
skillhub install timestamp-converter-1776275362
文件大小: 2.31 KB | 发布时间: 2026-4-16 16:31