gpt4 book ai didi

python - 将 30 分钟添加到从文本文件读取的时间并与当前时间进行比较

转载 作者:太空宇宙 更新时间:2023-11-04 09:02:02 25 4
gpt4 key购买 nike

我正在尝试制作一个小脚本来使用文本文件中的时间,然后将 30 分钟添加到该数字,然后与“当前时间”进行比较以查看是否已经超过 30 分钟...

import os
from time import time, sleep, strftime

with open('timecheck.txt') as timecheck:
last_timecheck = timecheck.read().strip()
print last_timecheck

currenttime = strftime('%H:%M:%S')
if last_timecheck + 30 >= currenttime:
if os.path.exists("../test.csv"):
with open("timecheck.txt", 'wb') as timecheck:
timecheck.write("1")
else:
currenttime = strftime('%H:%M:%S')
with open("timecheck.txt", 'wb') as timecheck:
timecheck.write(currenttime)

任何帮助将不胜感激,我不知道如何正确地做到这一点。

最佳答案

不是为当前时间创建字符串,解析从文件中读取的字符串,使用datetime.datetime.strftime()例如:

import datetime

last_timecheck = datetime.datetime.strptime(last_timecheck, '%H:%M:%S')
last_timecheck = datetime.datetime.combine(datetime.date.today(), last_timecheck.time())

if last_timecheck + datetime.timedelta(minutes=30) <= datetime.datetime.now():

这会检查超过 30 分钟

可能应该在写入文件的信息中包含日期。如果您不这样做,则 23:30:45 永远不会是 当天的“30 分钟前”。

如果您不需要时间戳是人类可读的,只需写自 UNIX 纪元以来的秒数:

timecheck.write(str(time.time()))

这是一个浮点值,您可以通过以下方式再次读取它:

last_timecheck = float(timecheck.read())

由于它是数字表示,因此您可以测试 30 分钟是否已过去:

if last_timecheck + 30 <= time.time():

关于python - 将 30 分钟添加到从文本文件读取的时间并与当前时间进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24303402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com