Python macro vs date field
In a python macro, I get the data from a range of cells from the calc using the command ‘.getDataArray()’, but in one of these cells there is a date field (05/05/21) which is converted to float (44321.0). How do I re-convert this to the string date format as it is displayed in the spreadsheet (05/05/21)?
I tried it with python’s datetime, but it didn’t work. Converted float (44321.0) to wrong date (01/01/1970)
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import uno
from com.sun.star.awt import MessageBoxButtons as MSG_BUTTONS
CTX = uno.getComponentContext()
SM = CTX.getServiceManager()
ODOC = XSCRIPTCONTEXT.getDocument()
def create_instance(name, with_context=False):
if with_context:
instance = SM.createInstanceWithContext(name, CTX)
else:
instance = SM.createInstance(name)
return instance
def openConsole(event=None):
"""
https://extensions.libreoffice.org/extensions/apso-alternative-script-organizer-for-python
"""
create_instance("apso.python.script.organizer.impl")
from apso_utils import console
#console()
console(BACKGROUND=0x0, FOREGROUND=0xD3D7CF)
return
def test(*args):
openConsole()
ODOC = XSCRIPTCONTEXT.getDocument()
oSheets = ODOC.getSheets()
planAgenda = oSheets.getByName("Sheet1")
cellContent = planAgenda.getCellRangeByName('A2:C3')
valueContent = cellContent.getDataArray()
import datetime
for line in valueContent:
for col in line:
if isinstance(col, float):
mydate = datetime.datetime.fromtimestamp(col).strftime("%d/%m/%Y")
text = f'''float date: {col} to string date: {mydate}'''
print(text)
Example file:
test.ods