python篇--定时产生文件

python篇--定时产生文件,第1张

python篇–定时产生文件

# !/usr/bin/python
# coding=UTF-8

import time
import os
import datetime


# 范围时间
def period_time(now_time):
    start_time = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '8:00', '%Y-%m-%d%H:%M')
    # 开始时间
    # print(start_time)
    end_time = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '22:00', '%Y-%m-%d%H:%M')
    # 结束时间
    # print(end_time)

    # 判断当前时间是否在范围时间内
    if start_time < now_time < end_time:
        print("是在这个时间区间内")
        return True
    else:
        return False


# 生成log文件
def number_log(file_name):
    now_time = datetime.datetime.now()
    print(now_time)
    flag = period_time(now_time)
    if flag:
        # 时间写入日志文件
        # datetime转str
        now_time = now_time.strftime('%Y-%m-%d %H:%M:%S')
        with open(file_name, 'a+', newline='') as screen_log:
            screen_log.writelines(now_time)
            screen_log.writelines("\n")
            screen_log.close()


if __name__ == '__main__':
    num = 1
    file = "./log/" + datetime.datetime.now().strftime("%Y-%m-%d")
    if not os.path.exists(file):
        os.makedirs(file)
    while True:
        file_name = file + "/" + str(num).zfill(3) + ".txt"
        number_log(file_name)
        time.sleep(10)  # 定时10s看一下
        num += 1


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/885767.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-14
下一篇2022-05-14

发表评论

登录后才能评论

评论列表(0条)

    保存