Skip to content

Instantly share code, notes, and snippets.

@hhanesand
Created September 19, 2023 10:48
Show Gist options
  • Save hhanesand/9628e0f0d920ae56c801c7add05778bb to your computer and use it in GitHub Desktop.
Save hhanesand/9628e0f0d920ae56c801c7add05778bb to your computer and use it in GitHub Desktop.
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta
from isodate import parse_duration
import json
import pytz # Import the required library
def convert_xml_to_json(xml_str):
namespace = {'ns': 'urn:iec62325.351:tc57wg16:451-6:balancingdocument:4:4'}
root = ET.fromstring(xml_str)
# Extract common properties from TimeSeries
resolution = root.find(".//ns:TimeSeries/ns:Period/ns:resolution", namespace).text
delta = parse_duration(resolution)
############ MODIFY ME TO CHANGE THE TIMEZONE
gmt = pytz.timezone('GMT')
amsterdam = pytz.timezone('Europe/Stockholm')
# Extract Point data and construct the desired JSON format
json_data = []
for period in root.findall(".//ns:TimeSeries/ns:Period", namespace):
start_time_gmt = datetime.strptime(period.find(".//ns:timeInterval/ns:start", namespace).text, "%Y-%m-%dT%H:%M%SZ")
start_time_gmt = gmt.localize(start_time_gmt) # Attach the GMT timezone information
start_time_amsterdam = start_time_gmt.astimezone(amsterdam) # Convert to Europe/Amsterdam timezone
date_str = start_time_amsterdam.strftime("%Y-%m-%d")
data_for_day = []
for point in period.findall(".//ns:Point", namespace):
price = float(point.find(".//ns:imbalance_Price.amount", namespace).text)
category = point.find(".//ns:imbalance_Price.category", namespace).text
if category != "A04":
continue
data_for_day.append(price)
if len(data_for_day) == 0:
continue
json_data.append({
"start": date_str,
"data": data_for_day
})
return json_data
# Read interval strings from the file
with open("/Users/hhanesand/Downloads/001-IMBALANCE_PRICES_202212312300-202308171100 2.xml", "r") as file:
xml_str = file.read()
json_output = convert_xml_to_json(xml_str)
with open("/Users/hhanesand/Developer/Enode/api/packages/aggregate/src/simulations/Data/SE1/2023/rawImbalance.json", "w") as f:
json.dump(json_output, f, indent=4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment