Python Desktop Activity Log App Code Review

I've recently (within the last month) started learning Python and am now building a few basic apps. One of the apps I've created is a sort of desktop monitoring tool, that attempts to build a list of all applications used within a specified time period.

Process -


Check whether the current time falls between the monitoring period
Create a record of what is currently being used
Save that record / entry to the log file
Repeat the process until the current time falls outside of the monitoring period
Once outside of monitoring period the Log file is renamed
End


I'd like to know whether some of you could spare a few minutes to review my code - Commenting on it's efficiency (or lack of), thoughts on how it could be improved and more. I do have some additional features to add (currently working on a UI). Right now I'm just looking comments.

Thanks in advance and apologies if I've posted in the wrong area.

from datetime import datetime
import os
import time
import psutil
import win32process

# When to start monitoring
start_time = datetime.now().strftime("%H:%M:%S")
# End Time - When to end monitoring
end_time = "08:55:00"
# Directory - Where to store activity log
directory = r"C:\Users\username\Documents"


def activity_log(s_time, e_time, dir_t):

    # act_app is used to return the active app/window
    act_app = ""

    # entry number/id
    num = 1000

    # monitoring start time
    p_start_time = s_time

    # monitoring end time
    p_end_time = e_time

    # File path / File name
    log_path = dir_t + "\\Log.csv"

    # Look into creating outer look to review current time or use out IF condition
    while p_start_time &lt;= datetime.now().strftime("%H:%M:%S") &lt;= p_end_time:

        # New record will be create IF different from the previous record
        if act_app != GetWindowText(GetForegroundWindow()) and act_app != " ":

            act_app = str.replace(GetWindowText(GetForegroundWindow()), " = ", ", ")
            today = datetime.today()
            num = num + 1
            pid = win32process.GetWindowThreadProcessId(GetForegroundWindow())
            app_name = psutil.Process(pid[-1]).name()

            with open(log_path, "a", encoding="utf-8") as LogFile:
                LogFile.write(f"{num}, {str.replace(act_app, ''''‎''', ' - ').replace(',', '')}, "
                              f"{app_name}, {today.strftime('''%d/%m/%Y''')}, "
                              f"{today.strftime('''%H:%M:%S''')} \n ")

        time.sleep(2)
        # Sleep/wait two seconds before attempting to create a new entry
    else:
        if os.path.isfile(log_path):
            # need to check if file exists before opening file
            with open(log_path, "a") as LogFile:
                LogFile.write(f"\n\n\n---- Desktop Activity Between {p_start_time} and {p_end_time} ----")
                # rename log file at the end of monitoring period
            os.rename(log_path, f"{dir_t}\\DesktopJ_ActLog_{datetime.now().strftime('''%d%m%Y_%H%M%S''')}.csv")
        else:
            print("No log created.")
            return "No log created"


activity_log(start_time, end_time, directory)
Welcome to CodeReview. Great first question!

Stringly-typed dates

Rather than holding onto dates as strings, you should be holding onto them as actual datetime objects. So this:

# When to start monitoring
start_time = datetime.now().strftime("%H:%M:%S")
# End Time - When to end monitoring
end_time = "08:55:00"


should instead be

# When to start monitoring
start_time = datetime.now()
# End Time - When to end monitoring
# This assumes that we are running early in the morning of the same
# day as the end_time
end_time = datetime.now().replace(hour=8, minute=55)


and

p_start_time &lt;= datetime.now().strftime("%H:%M:%S") &lt;= p_end_time:


should be

p_start_time &lt;= datetime.now() &lt;= p_end_time:


Parametric paths

# Directory - Where to store activity log
directory = r"C:\Users\username\Documents"


should not be hard-coded. Instead, accept it as a command-line argument, or an environmental variable, or store it in a config file.

Path management

# File path / File name
log_path = dir_t + "\\Log.csv"


is much easier with pathlib:

from pathlib import Path
# ...
dir_t = Path(...)
log_path = dir_t / 'Log.csv'


Logging

Strongly consider using the actual logging module instead of rolling your own. This will lend you more flexibility, and access to a more feature-rich logging framework. You can do everything you're doing now - have a file handler; have a custom formatter with your own chosen fields; etc.

In-place addition

        num = num + 1


can be

        num += 1