Modify this script so that there is the option to insert a range of dates…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Modify this script so that there is the option to insert a range of dates (startdatetime, enddatetime) in the command line in the format YYYYMMDDHHmm:
#!/usr/bin/env python3
• Scrapes http://nemweb.com.au/reports/CURRENT/Dispatch_SCADA/ • Downloads the X most recent *.zip files (specified via command line), sorted by timestamp • Extracts the CSV inside each zip • Inserts/Updates rows into nem_dispatch (ON CONFLICT DO UPDATE) • Cleans up temp files and logs every step
""" import os import sys import zipfile import time import requests import configparser import psycopg2 from datetime import datetime, timedelta from bs4 import BeautifulSoup from psycopg2 import OperationalError import argparse # Import the argparse module import re # Import the regular expression module
PROGRAM_VER = "dl_dispatch_v3.3.4" # Modified version name URL_DISPATCH = "http://nemweb.com.au/reports/CURRENT/Dispatch_SCADA/" HEADERS = {"User-Agent": "Mozilla/5.0"} TIMESTAMP = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
CWD = os.path.abspath(os.path.dirname(file)) + "/" DATA_DIR = os.path.join(CWD, "temp") LOG_DIR = os.path.join(CWD, "log") # Log directory LOGFILE = os.path.join(LOG_DIR, "dl_dispatch.log") INI_PATH = os.path.join(CWD, "aemo_config.ini")
os.makedirs(DATA_DIR, exist_ok=True)
def log(msg: str): print(msg) with open(LOGFILE, "a", encoding="utf-8") as fh: fh.write(f"{datetime.now():%Y-%m-%d %H:%M:%S} {msg}\n")
def connect_db(): cfg = configparser.ConfigParser() if not cfg.read(INI_PATH): log(f"ERROR: Unable to read {INI_PATH}") return None if not cfg.has_section("postgresql"): log(f"ERROR: Missing [postgresql] section in {INI_PATH}") return None try: params = {k: v for k, v in cfg.items("postgresql")} return psycopg2.connect(**params) except (OperationalError, psycopg2.Error) as err: log(f"DB connection error: {err}") return None
def exec_sql(sql, fetch="none", ctx=""): conn = connect_db() if not conn: return [] if fetch != "none" else False try: with conn: with conn.cursor() as cur: cur.execute(sql) if fetch == "all": return cur.fetchall() if fetch == "one": return cur.fetchone() return True except psycopg2.Error as err: log(f"psycopg2 error in {ctx}: {err}") return [] if fetch != "none" else False finally: conn.close()
def fetch_scada_filenames(): try: r = requests.get(URL_DISPATCH, headers=HEADERS, timeout=30) r.raise_for_status() soup = BeautifulSoup(r.text, "html.parser") files = [a.text.strip() for a in soup.find_all('a') if a.text.endswith('.zip') and 'PUBLIC_DISPATCHSCADA_' in a.text] log(f"Found {len(files)} SCADA zip files online.") return files except Exception as e: log(f"ERROR fetching SCADA page: {e}") return []
def download_file(filename): url = URL_DISPATCH + filename local_path = os.path.join(DATA_DIR, filename) if os.path.exists(local_path): return local_path # already downloaded try: r = requests.get(url, headers=HEADERS, stream=True, timeout=60) r.raise_for_status() with open(local_path, "wb") as fh: for chunk in r.iter_content(8192): fh.write(chunk) log(f"Downloaded {filename}") return local_path except Exception as e: log(f"Download failed for {filename}: {e}") return None
def unzip_get_csv(zip_path): try: with zipfile.ZipFile(zip_path) as z: csv_name = z.namelist()[-1] z.extract(csv_name, DATA_DIR) return os.path.join(DATA_DIR, csv_name) except Exception as e: log(f"Unzip failed for {zip_path}: {e}") return None
def import_csv_dispatch(csv_path): conn = connect_db() if not conn: return False try: inserted = 0 with open(csv_path, 'r') as fh, conn: with conn.cursor() as cur: for line in fh: if line.startswith(('C', 'I')): continue parts = line[24:].replace('/', '-').strip().split(',') if len(parts) < 4: continue try: # Ensure parts[3] is a valid datetime string for lastchanged lastchanged = parts[3] cur.execute( """ INSERT INTO nem_dispatch (settlement_date, duid, scada_value, lastchanged) VALUES (%s,%s,%s,%s) ON CONFLICT (settlement_date, duid) DO UPDATE SET scada_value = EXCLUDED.scada_value, lastchanged = EXCLUDED.lastchanged """, (parts[0], parts[1], parts[2], lastchanged)) # Pass lastchanged inserted += cur.rowcount except Exception as e: conn.rollback() log(f"SQL Error: {e}") # Log the specific SQL error raise # Re-raise the exception after logging log(f"Imported/Updated {inserted} rows from {os.path.basename(csv_path)}") return True except Exception as e: log(f"Import error {csv_path}: {e}") return False finally: conn.close()
def extract_datetime_from_filename(filename): """ Extracts datetime object from the filename. Filenames are like PUBLIC_DISPATCHSCADA_202505261805_0000000464981457.zip """ #match = re.search(r"PUBLIC_DISPATCHSCADA_(\d{12})(\d{12}).zip", filename) # Original regex match = re.search(r"PUBLIC_DISPATCHSCADA(\d{12})_.*.zip", filename) # Corrected regex if match: start_time_str = match.group(1) # e.g., 202505261805 try: start_time = datetime.strptime(start_time_str, "%Y%m%d%H%M") return start_time except ValueError: log(f"Could not parse datetime from filename: {filename}") return None else: log(f"Could not extract datetime pattern from filename: {filename}") return None
if name == "main": # Set up argument parser parser = argparse.ArgumentParser(description="Download and import AEMO Dispatch SCADA data.") parser.add_argument("-x", "--num_files", type=int, default=0, help="Number of most recent files to download (0 for all)")
args = parser.parse_args()
num_files_to_download = args.num_files
log(f"\nSTART {PROGRAM_VER} cwd={CWD}")
online_files = fetch_scada_filenames()
# Sort files by datetime extracted from filename (newest first)
online_files_sorted = sorted(online_files,
key=extract_datetime_from_filename,
reverse=True) # Sort newest first
if num_files_to_download > 0:
to_get = online_files_sorted[:num_files_to_download] # Get the 'x' most recent
log(f"Downloading the {num_files_to_download} most recent files.")
else:
to_get = online_files_sorted # Download all files
log("Downloading all available files.")
log(f"Files to download: {len(to_get)}")
for zip_name in to_get:
zip_path = download_file(zip_name)
if not zip_path:
continue
csv_path = unzip_get_csv(zip_path)
if csv_path and import_csv_dispatch(csv_path):
os.remove(zip_path)
os.remove(csv_path)
log(f"Cleaned {zip_name}")
log("FINISHED")
Certainly! I've modified your script to add two optional command-line arguments: --startdatetime and --enddatetime, both in the format YYYYMMDDHHmm. When these are provided, the script will download only files whose embedded datetime in the filename falls within the specified range (inclusive). If these arguments are omitted, the script behaves as before, downloading either the specified number of most recent files or all files.
Here is the updated script with the new date range filtering feature:
#!/usr/bin/env python3
# Previously known as data_download_vX.X.X.py
"""
AEMO DATA DOWNLOADER – Dispatch SCADA pipeline (FULL DOWNLOAD, LIMITED, OVERWRITE)
-------------------------------------------------
• Scrapes http://nemweb.com.au/reports/CURRENT/Dispatch_SCADA/
• Downloads the X most recent *.zip files (specified via command line), sorted by timestamp
• Extracts the CSV inside each zip
• Inserts/Updates rows into nem_dispatch (ON CONFLICT DO UPDATE)
• Cleans up temp files and logs every step
Prerequisites
-------------
1. Python 3.9+ with requests, beautifulsoup4, psycopg2-binary
2. Command line argument specifying the number of files to download or a date range.
"""
import os
import sys
import zipfile
import time
import requests
import configparser
import psycopg2
from datetime import datetime, timedelta
from bs4 import BeautifulSoup
from psycopg2 import OperationalError
import argparse
import re
# ── Constants ──────────────────────────────────────────────
PROGRAM_VER = "dl_dispatch_v3.3.4" # Modified version name
URL_DISPATCH = "http://nemweb.com.au/reports/CURRENT/Dispatch_SCADA/"
HEADERS = {"User-Agent": "Mozilla/5.0"}
TIMESTAMP = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# ── Paths ─────────────────────────────────────────────────
CWD = os.path.abspath(os.path.dirname(__file__)) + "/"
DATA_DIR = os.path.join(CWD, "temp")
LOG_DIR = os.path.join(CWD, "log") # Log directory
LOGFILE = os.path.join(LOG_DIR, "dl_dispatch.log")
INI_PATH = os.path.join(CWD, "aemo_config.ini")
os.makedirs(DATA_DIR, exist_ok=True)
os.makedirs(LOG_DIR, exist_ok=True)
# ── Logging helper ────────────────────────────────────────
def log(msg: str):
print(msg)
with open(LOGFILE, "a", encoding="utf-8") as fh:
fh.write(f"{datetime.now():%Y-%m-%d %H:%M:%S} {msg}\n")
# ── DB helpers ────────────────────────────────────────────
def connect_db():
cfg = configparser.ConfigParser()
if not cfg.read(INI_PATH):
log(f"ERROR: Unable to read {INI_PATH}")
return None
if not cfg.has_section("postgresql"):
log(f"ERROR: Missing [postgresql] section in {INI_PATH}")
return None
try:
params = {k: v for k, v in cfg.items("postgresql")}
return psycopg2.connect(**params)
except (OperationalError, psycopg2.Error) as err:
log(f"DB connection error: {err}")
return None
def exec_sql(sql, fetch="none", ctx=""):
conn = connect_db()
if not conn:
return [] if fetch != "none" else False
try:
with conn:
with conn.cursor() as cur:
cur.execute(sql)
if fetch == "all":
return cur.fetchall()
if fetch == "one":
return cur.fetchone()
return True
except psycopg2.Error as err:
log(f"psycopg2 error in {ctx}: {err}")
return [] if fetch != "none" else False
finally:
conn.close()
# ── Web scraping ──────────────────────────────────────────
def fetch_scada_filenames():
try:
r = requests.get(URL_DISPATCH, headers=HEADERS, timeout=30)
r.raise_for_status()
soup = BeautifulSoup(r.text, "html.parser")
files = [a.text.strip() for a in soup.find_all('a')
if a.text.endswith('.zip') and 'PUBLIC_DISPATCHSCADA_' in a.text]
log(f"Found {len(files)} SCADA zip files online.")
return files
except Exception as e:
log(f"ERROR fetching SCADA page: {e}")
return []
# ── Download / unzip / import ─────────────────────────────
def download_file(filename):
url = URL_DISPATCH + filename
local_path = os.path.join(DATA_DIR, filename)
if os.path.exists(local_path):
return local_path # already downloaded
try:
r = requests.get(url, headers=HEADERS, stream=True, timeout=60)
r.raise_for_status()
with open(local_path, "wb") as fh:
for chunk in r.iter_content(8192):
fh.write(chunk)
log(f"Downloaded {filename}")
return local_path
except Exception as e:
log(f"Download failed for {filename}: {e}")
return None
def unzip_get_csv(zip_path):
try:
with zipfile.ZipFile(zip_path) as z:
csv_name = z.namelist()[-1]
z.extract(csv_name, DATA_DIR)
return os.path.join(DATA_DIR, csv_name)
except Exception as e:
log(f"Unzip failed for {zip_path}: {e}")
return None
def import_csv_dispatch(csv_path):
conn = connect_db()
if not conn:
return False
try:
inserted = 0
with open(csv_path, 'r') as fh, conn:
with conn.cursor() as cur:
for line in fh:
if line.startswith(('C', 'I')):
continue
parts = line[24:].replace('/', '-').strip().split(',')
if len(parts) < 4:
continue
try:
lastchanged = parts[3]
cur.execute(
"""
INSERT INTO nem_dispatch (settlement_date, duid, scada_value, lastchanged)
VALUES (%s,%s,%s,%s)
ON CONFLICT (settlement_date, duid) DO UPDATE
SET scada_value = EXCLUDED.scada_value, lastchanged = EXCLUDED.lastchanged
""",
(parts[0], parts[1], parts[2], lastchanged))
inserted += cur.rowcount
except Exception as e:
conn.rollback()
log(f"SQL Error: {e}")
raise
log(f"Imported/Updated {inserted} rows from {os.path.basename(csv_path)}")
return True
except Exception as e:
log(f"Import error {csv_path}: {e}")
return False
finally:
conn.close()
# ── Helper function to extract datetime from filename ─────────────────────────────
def extract_datetime_from_filename(filename):
"""
Extracts datetime object from the filename.
Filenames are like PUBLIC_DISPATCHSCADA_202505261805_0000000464981457.zip
"""
match = re.search(r"PUBLIC_DISPATCHSCADA_(\d{12})_.*\.zip", filename)
if match:
start_time_str = match.group(1) # e.g., 202505261805
try:
start_time = datetime.strptime(start_time_str, "%Y%m%d%H%M")
return start_time
except ValueError:
log(f"Could not parse datetime from filename: {filename}")
return None
else:
log(f"Could not extract datetime pattern from filename: {filename}")
return None
# ── Main flow ─────────────────────────────────────────────
if __name__ == "__main__":
# Set up argument parser
parser = argparse.ArgumentParser(description="Download and import AEMO Dispatch SCADA data.")
parser.add_argument("-x", "--num_files", type=int, default=0,
help="Number of most recent files to download (0 for all)")
parser.add_argument("--startdatetime", type=str, default=None,
help="Start datetime in YYYYMMDDHHmm format (inclusive)")
parser.add_argument("--enddatetime", type=str, default=None,
help="End datetime in YYYYMMDDHHmm format (inclusive)")
args = parser.parse_args()
num_files_to_download = args.num_files
start_dt = None
end_dt = None
# Parse startdatetime and enddatetime if provided
if args.startdatetime:
try:
start_dt = datetime.strptime(args.startdatetime, "%Y%m%d%H%M")
except ValueError:
log(f"ERROR: Invalid startdatetime format. Use YYYYMMDDHHmm")
sys.exit(1)
if args.enddatetime:
try:
end_dt = datetime.strptime(args.enddatetime, "%Y%m%d%H%M")
except ValueError:
log(f"ERROR: Invalid enddatetime format. Use YYYYMMDDHHmm")
sys.exit(1)
if (start_dt and not end_dt) or (end_dt and not start_dt):
log("ERROR: Both startdatetime and enddatetime must be provided together.")
sys.exit(1)
log(f"\nSTART {PROGRAM_VER} cwd={CWD}")
online_files = fetch_scada_filenames()
# Sort files by datetime extracted from filename (newest first)
online_files_sorted = sorted(online_files,
key=extract_datetime_from_filename,
reverse=True)
# Filter by date range if specified
if start_dt and end_dt:
filtered_files = []
for f in online_files_sorted:
file_dt = extract_datetime_from_filename(f)
if file_dt is None:
continue
if start_dt <= file_dt <= end_dt:
filtered_files.append(f)
to_get = filtered_files
log(f"Downloading files between {start_dt} and {end_dt}: {len(to_get)} files found.")
else:
# If no date range, use num_files argument
if num_files_to_download > 0:
to_get = online_files_sorted[:num_files_to_download]
log(f"Downloading the {num_files_to_download} most recent files.")
else:
to_get = online_files_sorted
log("Downloading all available files.")
log(f"Files to download: {len(to_get)}")
for zip_name in to_get:
zip_path = download_file(zip_name)
if not zip_path:
continue
csv_path = unzip_get_csv(zip_path)
if csv_path and import_csv_dispatch(csv_path):
os.remove(zip_path)
os.remove(csv_path)
log(f"Cleaned {zip_name}")
log("FINISHED")
Download the 5 most recent files (old behavior):
./script.py -x 5
Download all files:
./script.py
Download files within a date range (inclusive):
./script.py --startdatetime 202505010000 --enddatetime 202505312359
Note: When using the date range options, the -x/--num_files argument is ignored.
If you want me to help you further with testing or packaging, just ask!