Python 从文本文件读取的时间加30分钟,并与当前时间进行比较

Python 从文本文件读取的时间加30分钟,并与当前时间进行比较,python,python-2.7,datetime,time,strftime,Python,Python 2.7,Datetime,Time,Strftime,我正在尝试制作一个小脚本来使用文本文件中的时间,然后在这个数字上加上30分钟,然后与“currenttime”进行比较,看看是否已经过去了30多分钟 import os from time import time, sleep, strftime with open('timecheck.txt') as timecheck: last_timecheck = timecheck.read().strip() print last_timecheck currenttime

我正在尝试制作一个小脚本来使用文本文件中的时间,然后在这个数字上加上30分钟,然后与“currenttime”进行比较,看看是否已经过去了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)

如果您能提供任何帮助,我将不胜感激。我不知道如何正确地执行此操作。

不要为当前时间创建字符串,而是解析从文件中读取的字符串,例如:

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():
这是一个浮点值,您可以使用以下命令再次读取它:

last_timecheck = float(timecheck.read())
由于它是一种数字表示形式,因此您可以测试30分钟是否已过去,并执行以下操作:

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

如果last_timecheck+30不是为当前时间创建字符串,而是解析从文件读取的字符串,例如:

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():
这是一个浮点值,您可以使用以下命令再次读取它:

last_timecheck = float(timecheck.read())
由于它是一种数字表示形式,因此您可以测试30分钟是否已过去,并执行以下操作:

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

如果last_timecheck+30,也许你可以同时拥有两个世界中最好的:人类可读和UNIX秒。我很难想出如何使用datetime版本,但UNIX方式很简单,我之所以使用这种方式,是因为我不太关心它的可读性。也许你可以同时拥有两个世界中最好的:人类可读和UNIX我努力想弄清楚如何使用datetime版本,但是unix的方式很简单,我使用这种方式是因为我不在乎它的可读性。