I have data in seconds that I need to convert to H:MM:SS. When this data comes in it also has a date field in a separate column. I need to convert the seconds data into H:MM:SS but keep the date field as a date. I need the output to look like the desired output in Excel.
Example desired output: excel output
I've tried using Excel writer and setting the default format of date_format or datetime_format however this converts all datetime columns in the excel file. Previous responses from jmcnamara indicates that this is because cell format takes precedence over column or row format.
Here is some sample code that i've gotten to work but it's not very pythonic. It involves saving the dataframe to excel but then re-opening that exact file.
# imports
import pandas as pd
import random
from openpyxl import load_workbook
from openpyxl.styles import NamedStyle
# generate data
numbers = (random.sample(range(500, 2000), 10))
df = pd.DataFrame(numbers)
df.rename(columns={df.columns[0]:'Time'}, inplace=True)
# convert to time
df['Timestamp'] = pd.to_timedelta(df['Time'], unit='s') + pd.Timestamp(0)
#df['Openpyxl Time'] = pd.to_timedelta(df['Time'], unit='s') + pd.Timestamp(0)
# write to file
writer = pd.ExcelWriter('test.xlsx', engine = 'xlsxwriter')
df.to_excel(writer, sheet_name= 'Sheet 1', index=False)
writer.save()
# load just created file
wb = load_workbook('test.xlsx')
ws = wb.active
# set format style
date_style = NamedStyle(name='datetime', number_format='h:mm:ss')
# simple way to format but also formats column header
for cell in ws['C']:
cell.style = date_style
#more complex way to format, but does not format column header
# for row in ws.iter_rows('C{}:C{}'.format(ws.min_row+1, ws.max_row)):
# for cell in row:
# cell.style = date_style
wb.save('test.xlsx')
wb.close()
How do i re-write this to not have to re-open the excel file to change the different columns to different datetime formats?
The desired output also can't be read as a string in excel. I need to be able to derive averages and sum from the timestamps.
Thanks!