Code a free trial tracker in python
- User
Code a free trial tracker in python
- Assistant
To create a free trial tracker in Python, you can use the following code. This script allows you to add, view, delete, and check free trials. It stores the trial information in a JSON file (
free_trials.json) so that the data persists between runs.Here's the complete code:
import json from datetime import datetime, timedelta import os class FreeTrial: def __init__(self, service_name, start_date, end_date, notes): self.service_name = service_name self.start_date = start_date self.end_date = end_date self.notes = notes def to_dict(self): return { 'service_name': self.service_name, 'start_date': self.start_date.strftime("%Y-%m-%d"), 'end_date': self.end_date.strftime("%Y-%m-%d"), 'notes': self.notes } @staticmethod def from_dict(data): return FreeTrial( data['service_name'], datetime.strptime(data['start_date'], "%Y-%m-%d"), datetime.strptime(data['end_date'], "%Y-%m-%d"), data.get('notes', '') ) DATA_FILE = 'free_trials.json' def load_data(): if os.path.exists(DATA_FILE): with open(DATA_FILE, 'r') as f: data = json.load(f) trials = [FreeTrial.from_dict(item) for item in data] return trials else: return [] def save_data(trials): data = [trial.to_dict() for trial in trials] with open(DATA_FILE, 'w') as f: json.dump(data, f, indent=4) def add_new_trial(trials): service_name = input("Enter service name: ") while True: start_date_str = input("Enter start date (YYYY-MM-DD) [today]: ") if not start_date_str.strip(): start_date = datetime.today() break else: try: start_date = datetime.strptime(start_date_str, "%Y-%m-%d") break except ValueError: print("Invalid date format. Please enter in YYYY-MM-DD format.") while True: end_date_str = input("Enter end date (YYYY-MM-DD) or duration in days (e.g., +7): ") if end_date_str.startswith('+'): try: days = int(end_date_str.strip('+')) end_date = start_date + timedelta(days=days) break except ValueError: print("Invalid duration. Please enter a number of days, e.g., +7") else: try: end_date = datetime.strptime(end_date_str, "%Y-%m-%d") break except ValueError: print("Invalid date format. Please enter in YYYY-MM-DD format or duration in days starting with '+'.") notes = input("Notes (optional): ") trial = FreeTrial(service_name, start_date, end_date, notes) trials.append(trial) print(f"Free trial for {service_name} added, ending on {end_date.strftime('%Y-%m-%d')}.") def view_trials(trials): if not trials: print("No free trials to display.") return print("{:<4} {:<20} {:<12} {:<12} {:<10} {:<}".format('No.', 'Service', 'Start Date', 'End Date', 'Days Left', 'Notes')) print("-" * 80) today = datetime.today() for idx, trial in enumerate(trials): days_left = (trial.end_date - today).days days_left_str = str(days_left) if days_left >=0 else 'Expired' print("{:<4} {:<20} {:<12} {:<12} {:<10} {:<}".format( idx+1, trial.service_name, trial.start_date.strftime("%Y-%m-%d"), trial.end_date.strftime("%Y-%m-%d"), days_left_str, trial.notes )) def delete_trial(trials): view_trials(trials) if not trials: return while True: selection = input("Enter the number of the trial to delete (or 'c' to cancel): ") if selection.lower() == 'c': break try: idx = int(selection) -1 if 0 <= idx < len(trials): removed_trial = trials.pop(idx) print(f"Deleted trial for {removed_trial.service_name}.") break else: print("Invalid selection.") except ValueError: print("Invalid input.") def check_trials(trials): today = datetime.today() print("Checking trials:") for trial in trials: days_left = (trial.end_date - today).days if days_left < 0: print(f"Trial for {trial.service_name} has expired on {trial.end_date.strftime('%Y-%m-%d')}.") elif days_left == 0: print(f"Trial for {trial.service_name} expires today.") elif days_left <=3: print(f"Trial for {trial.service_name} expires in {days_left} day(s), on {trial.end_date.strftime('%Y-%m-%d')}.") print("Done checking trials.") def main(): trials = load_data() while True: print("\nFree Trial Tracker") print("==================") print("1. Add new trial") print("2. View trials") print("3. Delete a trial") print("4. Check trials") print("5. Save and Exit") choice = input("Select an option (1-5): ") if choice == '1': add_new_trial(trials) elif choice == '2': view_trials(trials) elif choice == '3': delete_trial(trials) elif choice == '4': check_trials(trials) elif choice == '5': save_data(trials) print("Data saved. Exiting.") break else: print("Invalid selection. Try again.") if __name__ == "__main__": main()Usage:
-
Add New Trial: Enter the service name, start date (leave blank for today), and end date (either a specific date in
YYYY-MM-DDformat or a duration like+7for 7 days from the start date). Optionally, you can add notes. -
View Trials: Displays all the stored trials with their details and days left until expiration.
-
Delete a Trial: Allows you to remove a trial from the tracker by selecting its number from the displayed list.
-
Check Trials: Checks for trials that have expired or are about to expire (within 3 days) and prints notifications.
-
Save and Exit: Saves the current state to the JSON file and exits the program.
Example Run:
Free Trial Tracker ================== 1. Add new trial 2. View trials 3. Delete a trial 4. Check trials 5. Save and Exit Select an option (1-5): 1 Enter service name: Netflix Enter start date (YYYY-MM-DD) [today]: Enter end date (YYYY-MM-DD) or duration in days (e.g., +7): +30 Notes (optional): One-month free trial Free trial for Netflix added, ending on 2023-11-30. Free Trial Tracker ================== 1. Add new trial 2. View trials 3. Delete a trial 4. Check trials 5. Save and Exit Select an option (1-5): 2 No. Service Start Date End Date Days Left Notes -------------------------------------------------------------------------------- 1 Netflix 2023-10-31 2023-11-30 30 One-month free trial Free Trial Tracker ================== 1. Add new trial 2. View trials 3. Delete a trial 4. Check trials 5. Save and Exit Select an option (1-5): 5 Data saved. Exiting.Notes:
- The program uses the
datetimemodule to handle dates. - It stores data in a JSON file named
free_trials.json. Ensure that the directory where you run the script has write permissions. - When entering dates, make sure to use the
YYYY-MM-DDformat. - For durations, input
+NwhereNis the number of days from the start date.
This script should help you keep track of your free trials and remind you before they expire.
-