Pravat
Pravat

Reputation: 329

Change Logfile Name every 15 minutes without overwrite

I need to write my program output to a log file whose name should change every 15 minutes and currently I am doing this way.

import time
from datetime import datetime

FullLog = datetime.today().strftime("Prog1TempLog1_%d_%m_%Y") + ".txt"

today0915 = datetime.now().replace(hour=9, minute=15, second=0,microsecond=0)
today0930 = datetime.now().replace(hour=9, minute=30, second=0,microsecond=0)
today0945 = datetime.now().replace(hour=9, minute=45, second=0,microsecond=0)
today1000 = datetime.now().replace(hour=10, minute=0, second=0,microsecond=0)
today1015 = datetime.now().replace(hour=10, minute=15, second=0,microsecond=0)

while <my condition>:

    if datetime.now() > today0915 and datetime.now() <= today0930:
        FullLog = datetime.today().strftime("Prog1Log1_%d_%m_%Y") + ".txt"
    if datetime.now() > today0930 and datetime.now() <= today0945:
        FullLog = datetime.today().strftime("Prog1Log2_%d_%m_%Y") + ".txt"
    if datetime.now() > today0945 and datetime.now() <= today1000:
        FullLog = datetime.today().strftime("Prog1Log3_%d_%m_%Y") + ".txt"
    if datetime.now() > today0945 and datetime.now() <= today1000:
        FullLog = datetime.today().strftime("Prog1Log4_%d_%m_%Y") + ".txt"
    if datetime.now() > today1000 and datetime.now() <= today1015:
        FullLog = datetime.today().strftime("Prog1Log5_%d_%m_%Y") + ".txt"

    print("Time", datetime.now(), "FileName:", FullLog)

    time.sleep(1)

Is there any dynamic way to do this procedure.

Upvotes: 0

Views: 69

Answers (1)

kawadhiya21
kawadhiya21

Reputation: 2528

During while loop, get the current time. Then figure out how many minutes does it have. For ex., 10:20 has 20 minutes. Now divide it by 15 and add 1 to get the file name.

now = datetime.today().minute
log_seq = num//15 + 1 #just check edge cases around 60 and 00 .. // for python3
FullLog = datetime.today().strftime("Prog1Log"+log_seq+"_%d_%m_%Y") + ".txt"

Upvotes: 2

Related Questions