python - 使用 datetime 作为存储在 JSON 中的计时器
问题描述
我正在尝试datetime
从 JSON 中的存储datetime
值中减去,以查看是否已经过了 2 分钟才能再次使用命令。当我使用该命令时,每次 JSON 值更新为“0”时,即使我打印currentime
它也会给我想要存储的值。我已经尝试更改timer[id]["flytimer"] = (datetime.datetime.utcnow() - epoch).total_seconds()
为timer[id]["flytimer"] = 0
但仍然得到相同的结果
try:
with open("timer.json") as fp:
timer = json.load(fp)
except Exception:
timer = {}
def save_timer():
with open("timer.json", "w+") as fp:
json.dump(timer, fp, sort_keys=True, indent=4)
def add_flytimer(user: discord.User, flytimer: int):
id = user.id
if id not in timer:
timer[id] = {}
timer[id]["flytimer"] = (datetime.datetime.utcnow() - epoch).total_seconds()
save_timer()
def get_flytimer(user: discord.User):
id = user.id
if id in timer:
return timer[id].get("flytimer", 0)
return 0
def reset_flytimer(user: discord.User, flytimer: int):
id = user.id
if id in timer:
timer[id]["flytimer"] = 0
print("{} flight timer reset".format(user.name))
save_timer()
epoch = datetime.datetime.utcfromtimestamp(0)
currenttime = (datetime.datetime.utcnow() - epoch).total_seconds()
if message.content.startswith('!flight'):
print(currenttime)
if get_flytimer is None:
add_flytimer(message.author, currenttime)
print(currenttime)
print(get_flytimer(message.author))
await client.send_message(message.channel, "{} takes a flight to NY".format(message.author))
else:
takeflight = currenttime - get_flytimer(message.author)
if takeflight >= 120:
add_flytimer(message.author,currenttime)
print(get_flytimer(message.author))
await client.send_message(message.channel, "{} takes a flight to NY".format(message.author))
else:
await client.send_message(message.channel, "{} you still have {} seconds until the next flight".format(message.author, takeflight))
解决方案
推荐阅读
- css - 无法在 Firefox 中使用 Materialize 1.0.0 输入密码输入字段
- sql - 在会话日志表中查找最大并发用户
- objective-c - Apple Metal Element-wise 矩阵乘法(Hadamard Product)
- spring-boot - Kafka - 如何在 springboot yml 文件中定义用户和密码?
- android - 在 PhoneGap 项目中添加 Google AdMob
- python - 在 Python 中将 API 数据附加到 Pandas DataFrame
- ms-access - 在 Access 中查找具有特定条件的最新记录
- swift - OpenFace CoreML 模型。没有人脸检测
- php - Gmail API 未阅读完整的电子邮件
- javascript - 如何制作使图像从右向左移动的图像滑块?