简体   繁体   English

如何用日期时间字符串减去 datetime.now 对象?

[英]How can I subtract a datetime.now object with a datetime string?

I have a server bot where I want to make a certain command usable only once every 24 hours.我有一个服务器机器人,我想让某个命令每 24 小时只能使用一次。 Each time the user uses the command, I store datetime.now in my SQL database in %H:M:%S format so the variable may looks like this:每次用户使用该命令时,我都会将 datetime.now 以 %H:M:%S 格式存储在我的 SQL 数据库中,因此变量可能如下所示:

b = "07:17:45"

I would like to somehow subtract that stored string with datetime.datetimenow() each time the user uses the command to get an output of the remaining time left to check if 24 hours has passed or not.每次用户使用该命令来获取剩余时间的输出以检查 24 小时是否已经过去时,我想以某种方式用 datetime.datetimenow() 减去存储的字符串。

You may want to use strptime,你可能想使用 strptime,

from datetime import datetime
now = datetime.now()
then = datetime.strptime('07:17:45', '%H:%M:%S')
then = datetime.combine(now.date(), then.time())

delta = now - then
time_in_seconds = delta.total_seconds()
time_in_minutes = time_in_seconds / 60
time_in_hours = time_in_minutes / 60

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM