首页 > 解决方案 > Python修复了字典中的未来时间戳

问题描述

我有一本字典,用于存储用户名和未来的时间戳。问题是未来的时间戳不是固定的,每次函数运行时都会转移到未来。因此,我无法将当前时间与存储的时间戳进行比较。

有没有办法在字典中存储固定的未来时间戳并在整个程序运行时保持它们不变?

例如:

users = {}

def recordUser(username):
   
    futureT = datetime.now() + timedelta(seconds=10)
    if username not in users:
        users[username] = futureT

currentT = datetime.now()

if username in users:
     if users[username] > currentT:
         print("User is blocked")

recordUser(username)
print("Current time:", currentT)
print("Blocked until:", users[username]) 

我得到的输出是未来时间不断更新到当前时间 + 10 秒,这是可以理解的,因为我在当前时间上增加了 10 秒。但是有没有办法将未来时间作为固定值存储在字典中,即当前时间加上 10 秒?

假设字典中记录用户未来时间的时间:2021-04-16 07:43:00.465934

如果我们再次运行它2021-04-16 07:44:28.465934,输出是:

Current time: 2021-04-16 07:44:28.465934
Blocked until: 2021-04-16 07:44:38.465647

预期输出为:

Current time: 2021-04-16 07:44:28.465934
Blocked until: 2021-04-16 07:43:00.465934

编辑:

该文件是服务器并持续运行,而客户端加入连接。据我了解,只要 server.py 正在运行,字典中的时间戳就应该保持不变。

标签: pythonpython-3.x

解决方案


推荐阅读