vendredi 9 juin 2023

Python Date Generation And Random Date Generation

All though, it may not look like it, they do the exact same thing, and I don't know which one is more reliable (Error handling and simplicity):

    def gen_date(self):
        start_date = simpledialog.askstring("Set Date Range", "Enter start date (MM/DD/YYYY):")
        end_date = simpledialog.askstring("Set Date Range", "Enter end date (MM/DD/YYYY):")
        if start_date and end_date:
            start_date = datetime.strptime(start_date, "%m/%d/%Y")
            end_date = datetime.strptime(end_date, "%m/%d/%Y")
            delta = (end_date - start_date).days
            random_days = random.randint(0, delta)
            random_date = start_date + timedelta(days=random_days)
            random_date = max(random_date, start_date)
            random_date = min(random_date, end_date)

Or

    def date_range(self):
        start = simpledialog.askstring("Set Date Range", "Enter start date (MM/DD/YYYY):")
        if start:
            try:
                start = datetime.strptime(start, "%m/%d/%Y")
                end = simpledialog.askstring("Set Date Range", "Enter end date (MM/DD/YYYY):")
                if end:
                    end = datetime.strptime(end, "%m/%d/%Y")
                    if start > end:
                        raise ValueError("Start date must be earlier than end date")
                    delta = (end - start).days
                    random_days = random.randint(0, delta)
                    gen_date = end - timedelta(days=random_days)
                    self.text.insert("insert", gen_date.strftime("%B %d, %Y"))
                else:
                    messagebox.showerror("Error", "End date is required")
            except ValueError as e:
                messagebox.showerror("Error", str(e))

The first one is shorter, but it looks too good to be true. If they both have good error handling, then it should be the one that is shorter. the first one is 932 characters, the second one is 632. Character amount matters to me, because I want it to be as little characters as possible, taking up less storage, meaning a larger audience can reach it.

I have tried to remove the question from 1, because I know that 2 will definitely NOT work if just remove the question. The error I get is:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\[NAME]\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 1948, in __call__
    return self.func(*args)
           ^^^^^^^^^^^^^^^^
  File "C:\Users\[NAME]\Downloads\CandelX\CandelX.py", line 203, in gen_date
    start_date = datetime.strptime(start_date, "%m/%d/%Y")
                                   ^^^^^^^^^^
UnboundLocalError: cannot access local variable 'start_date' where it is not associated with a value

I have tried AI, which it didn't understand what I was asking.




Aucun commentaire:

Enregistrer un commentaire