Converting an excel file to a specific Json in python using openpyxl library with datetime

2024/11/19 7:44:16

enter image description here

I have the Excel data with the format shown in the image preview. How can I convert it into a JSON using Python?

Expected Output:

file_name = [ { A: Measurement( calculated_date=datetime(2022, 10, 1, 4, 18), X1=1, X2=4 ), B: Measurement( calculated_date=datetime(2022, 10, 1, 4, 18), X1=1.2, X2=4.1 ), C: Measurement( calculated_date=datetime(2022, 10, 1, 4, 18), X1=1, X2=4 ) }, { A: Measurement( calculated_date=datetime(2022, 10, 2, 3, 18), X1=1.1, X2=4 ), B: Measurement( calculated_date=datetime(2022, 10, 2, 3, 18), X1=1, X2=4.2 ), C: Measurement( calculated_date=datetime(2022, 10, 2, 3, 18), X1=1, X2=4 ) }, { A: Measurement( calculated_date=datetime(2022, 10, 3, 9, 48), X1=1.3, X2=4.1 ), B: Measurement( calculated_date=datetime(2022, 10, 3, 9, 48), X1=1, X2=4.1 ), C: Measurement( calculated_date=datetime(2022, 10, 3, 9, 48), X1=1.2, X2=3.9 ) } ]

Answer

This should get the desired output:

import openpyxl
from openpyxl.utils import get_column_letter
from datetime import datetime
import jsondef load_excel_data(file_path):workbook = openpyxl.load_workbook(file_path)sheet = workbook.activereturn sheetdef convert_excel_datetime(excel_datetime_str):return datetime.strptime(str(excel_datetime_str), '%Y-%m-%d %H:%M:%S')def create_measurement_dict(time, x1, x2):return {'calculated_date': time,'X1': x1,'X2': x2}def main():excel_file = 'test.xlsx'sheet = load_excel_data(excel_file)json_data = []current_date = Noneentry = {}for row in sheet.iter_rows(min_row=2, values_only=True):device_id, row_time, x1, x2 = rowparsed_time = convert_excel_datetime(row_time)if parsed_time.date() != current_date:if current_date:json_data.append(entry)current_date = parsed_time.date()entry = {}measurement = create_measurement_dict(parsed_time, x1, x2)entry[device_id] = 'Measurement(' + str(measurement) + ')'json_data.append(entry)print(json.dumps(json_data, indent=4))if __name__ == "__main__":main()

Output:

[{"A": "Measurement({'calculated_date': datetime.datetime(2022, 10, 1, 4, 18), 'X1': 1, 'X2': 4})",    "B": "Measurement({'calculated_date': datetime.datetime(2022, 10, 1, 4, 18), 'X1': 1.2, 'X2': 4.1})","C": "Measurement({'calculated_date': datetime.datetime(2022, 10, 1, 4, 18), 'X1': 1, 'X2': 4})"     },{"A": "Measurement({'calculated_date': datetime.datetime(2022, 10, 2, 3, 18), 'X1': 1.1, 'X2': 4})","B": "Measurement({'calculated_date': datetime.datetime(2022, 10, 2, 3, 18), 'X1': 1, 'X2': 4.2})","C": "Measurement({'calculated_date': datetime.datetime(2022, 10, 2, 3, 18), 'X1': 1, 'X2': 4})"},{"A": "Measurement({'calculated_date': datetime.datetime(2022, 10, 3, 9, 48), 'X1': 1.3, 'X2': 4.1})","B": "Measurement({'calculated_date': datetime.datetime(2022, 10, 3, 9, 48), 'X1': 1, 'X2': 4.1})","C": "Measurement({'calculated_date': datetime.datetime(2022, 10, 3, 9, 48), 'X1': 1.2, 'X2': 3.9})"}
]
https://en.xdnf.cn/q/118566.html

Related Q&A

How to find a word in a string in a list? (Python)

So im trying to find a way so I can read a txt file and find a specific word. I have been calling the file with myfile=open(daily.txt,r)r=myfile.readlines()that would return a list with a string for ea…

How to make a new default argument list every time [duplicate]

This question already has answers here:The Mutable Default Argument in Python(34 answers)Closed 10 years ago.I have the following setup:def returnList(arg=["abc"]):return arglist1 = returnLis…

How does one reorder information in an XML document in python 3?

Lets suppose I have the following XML structure:<?xml version="1.0" encoding="utf-8" ?> <Document><CstmrCdtTrfInitn><GrpHdr><other_tags>a</other_t…

Python - Replace only exact word in string [duplicate]

This question already has answers here:How to match a whole word with a regular expression?(4 answers)Closed 4 years ago.I want to replace only specific word in one string. However, some other words h…

How to write Hierarchical query in PYTHON

The given input is like:EMPLOYEE_ID NAME MANAGER_ID101 A 10102 B 1110 C 111 D 11 E nullEmployee Cycle LEVEL Path10…

Unable to launch selenium with python in mac

Im facing an issue with selenium with python in Mac OS.. Python 2.7 pydev 3.0My sample codefrom selenium import webdriver driver = webdriver.Firefox() driver.get("https://www.formsite.com/") …

Memory error In instantiating the numpy array

I have a list A of a 50,000 elements and each element is an array of shape (102400) I tried instantiating an array B.B=numpy.array(A)But this throws an exception MemoryError.I know that the memory and …

Setting column names in a pandas dataframe (Python)

When setting a column name for a pandas dataframe, why does the following work:df_coeff = pd.DataFrame(data = lm.coef_, index = X.columns, columns = [Coefficient])While this does not workdf_coeff = pd.…

Check that Python function does not modify argument?

You know how in Python, if v is a list or a dictionary, its quite common to write functions that modify v in place (instead of just returning the new value). Im wondering if it is possible to write a c…

What Python 3 version for my Django project

I will try to port my Python 2.7 with Django to Python 3. But now my question is what version is the most stable one today? Ive heard people use 3.2 and 3.4 and recommend it. But now Im asking you guy…