vinci1it2000 / formulas

Excel formulas interpreter in Python.
https://formulas.readthedocs.io/
European Union Public License 1.1
342 stars 75 forks source link

Calculation fails on dates #140

Open emilzak opened 3 months ago

emilzak commented 3 months ago

The problem I created two user-defined functions, BSDATE and BSNUMBER. BSDATE returns datetime.date and BSNUMBER returns int. Operations performed on numbers work well. Ops on dates fail with #VALUE!

I've attached the excel and python code.

Please look at D1 (Error) and D2 ( Success )

import datetime
import formulas

def _BSDATE(m):
    return datetime.date(2024,m,30)
def _BSNUMBER(n):
    return n

FUNCTIONS = formulas.get_functions()
FUNCTIONS["BSDATE"] = _BSDATE
FUNCTIONS["BSNUMBER"] = _BSNUMBER

xl_model = formulas.ExcelModel().loads("333.xlsx").finish()
xl_model.calculate()
xl_model.write(dirpath="output")

Python: 3.8 OS: macOS Sonoma

Here is the result of the calculation

image

Please advise, and thanks for your work!

333.xlsx

UPDATE 1:

  1. I tried to return formatted string from _BSDATE function - same result
  2. If i set a string value instead of the function _BSDATE in the excel calculation works correctly
vinci1it2000 commented 1 day ago

The dates in Excel are numbers with only a specific formatting. You can use the formulas.functions.date._int2date function that converts the date serial_number to (year, month, day). The formulas.functions.date._text2datetime function that converts the text to (year, month, day).

Let me know if it is straightforward for you.