【问题标题】:Add 30 minutes to a time read from a text file and compare against current time将 30 分钟添加到从文本文件中读取的时间并与当前时间进行比较
【发布时间】:2014-06-19 09:36:57
【问题描述】:

我正在尝试制作一个小脚本来使用文本文件中的时间,然后在该数字上加上 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)

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

【问题讨论】:

    标签: python python-2.7 datetime time strftime


    【解决方案1】:

    不是为当前时间创建字符串,而是解析从文件中读取的字符串,例如使用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():
    

    【讨论】:

    • 也许你可以两全其美:人类可读和 UNIX 秒。
    • 我很难弄清楚如何使用 datetime 版本,但 unix 方式很简单,我正在使用这种方式,因为我不在乎它的可读性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多