pythonpandasstyleframe

styleframe.ExcelWriter's date_format and datetime_format is not work~


Today I use styleframe to help beautify my Excel.

While I add the date_format or datetime_format, it's not work.

def _write_xlsx(self, filename, data, columns):
    print(f'Writing {filename} length: {len(data)}')

    data_frame = pandas.DataFrame(data, columns=columns)
    excel_writer = StyleFrame.ExcelWriter(
        filename,
        date_format='YYYY-MM-DD',  # TODO: not work!
        datetime_format='YYYY-MM-DD HH:MM:SS',  # TODO: not work!
    )
    style_frame = StyleFrame(data_frame)
    style_frame.to_excel(
        excel_writer=excel_writer,
        best_fit=columns,
        columns_and_rows_to_freeze='B2',
        row_to_add_filters=0,
    )
    excel_writer.save()

I changed the input time object into 'datetime.datetime' or 'Pandas.Timestamp', It's still not working.

pandas.to_datetime(pandas_col.get('my_time')).to_pydatetime()  # datetime.datetime
pandas.to_datetime(pandas_col.get('my_time'))  # Pandas.Timestamp

I read styleframe's source code. StyleFrame.ExcelWriter is pandas.ExcelWriter.

pandas.ExcelWriter's init func has date_format and datetime_format, and it looks like used date_format and datetime_format.

So, am I have sth. wrong?


Solution

  • styleframe uses Styler objects to represent and apply styles. It can specify different formats for date, time and datetime objects.

    See this example:

    from styleframe import StyleFrame, Styler
    
    sf = StyleFrame({'a': [datetime.now().date(), datetime.now()]},
                    Styler(date_format='YYYY-MM-DD',
                           date_time_format='YYYY-MM-DD HH:MM:SS'))
    sf.to_excel('dates.xlsx').save()
    

    The only oversight is that pandas converts date objects to Timestamp objects, so the format passed as date_format to Styler is not used (because internally styleframe uses the date_time_format for Timestamp objects).