问题描述
with proc.oneshot():
uptime = timedelta(seconds=time() - proc.create_time())
uptime_minutes,uptime_seconds = divmod(uptime.seconds,60)
uptime_hours,uptime_minutes = divmod(uptime_minutes,60)
uptime_days,uptime_hours = divmod(uptime_hours,24)
if uptime_seconds:
frmt_uptime = '{:01} Seconds'.format(
int(uptime_seconds))
if uptime_minutes:
frmt_uptime = '{:01} Minutes,{:01} Seconds'.format(
int(uptime_minutes),int(uptime_seconds))
if uptime_hours:
frmt_uptime = '{:01} Hours,{:01} Minutes,{:01} Seconds'.format(
int(uptime_hours),int(uptime_minutes),int(uptime_seconds))
if uptime_days:
frmt_uptime = '{:01} Day(s),{:01} Hour(s),{:01} Minute(s),{:01} Second(s)'.format(
int(uptime_days),int(uptime_hours),int(uptime_seconds))
print(frmt_uptime)
现在我希望它显示天数,但由于某种原因,目前它持续 23 小时 59 分 59 秒,然后应该显示 1 天。一秒后 1 天 1 秒。一分钟后,1天1分钟。但目前它似乎只是在 24 小时后重新启动,这让我相信我几天的锻炼方式出了问题。
解决方法
你处理时间的方式,你需要.total_seconds
。
但是,您的代码不会显示“1 天 1 秒”,因为 if uptime_days:
中的格式字符串将始终包含小时和分钟。
建议:
from datetime import timedelta,datetime
def uptime(create_time: datetime):
uptime = datetime.now() - create_time
uptime_minutes,uptime_seconds = divmod(uptime.total_seconds(),60)
uptime_hours,uptime_minutes = divmod(uptime_minutes,60)
uptime_days,uptime_hours = divmod(uptime_hours,24)
time_parts = []
if uptime_days:
time_parts.append('{:01} Days'.format(int(uptime_days)))
if uptime_hours:
time_parts.append('{:01} Hours'.format(int(uptime_hours)))
if uptime_minutes:
time_parts.append('{:01} Minutes'.format(int(uptime_minutes)))
if uptime_seconds:
time_parts.append('{:01} Seconds'.format(int(uptime_seconds)))
return ",".join(time_parts)
print(uptime(datetime(2021,2,11,16,20)))
,
我不太确定您的代码有什么问题,但我的方法如下:
from datetime import datetime
bot = commands.Bot(...) # Or `discord.Client`,depends what you're using
bot.uptime = datetime.utcnow()
在命令中只需获取增量并对其进行格式化
@bot.command()
async def uptime(ctx):
now = datetime.utcnow()
delta = now - bot.uptime
# Feel free to format it as you want
seconds = int(delta.total_seconds())
hours,remainder = divmod(seconds,3600)
minutes,seconds = divmod(remainder,60)
if hours >= 24:
days,hours = divmod(hours,24)
message = f"Uptime: {days} day(s),{hours} hour(s),{minutes} minute(s),{seconds} second(s)"
else:
message = f"Uptime: {hours} hour(s),{seconds} second(s)"
await ctx.send(message)