Python xlwt with Date Time Formats for Excel Cells
In this Python xlwt tutorial we learn how to set the date time format for Excel cell during writing Excel file with xlwt library.
Install xlwt package
Firstly we need to install the xlwt package by the command below.
pip install xlwt
How to format date time for Excel cells using xlwt
In order to set format for the cell we use the XFStyle object and set num_format_str as below.
style = xlwt.XFStyle()
style.num_format_str = 'D-MMM-YY'
sheet.write(i, 1, datetime.now(), style)
The following example Python program will show you how to write Excel file with different date time format cells.
datetime-formats.py
import xlwt
from datetime import datetime
workbook = xlwt.Workbook()
sheet = workbook.add_sheet("Formats")
header_font = xlwt.Font()
header_font.name = 'Arial'
header_font.bold = True
header_style = xlwt.XFStyle()
header_style.font = header_font
sheet.write(0, 0, 'Format', header_style)
sheet.write(0, 1, 'Value', header_style)
formats = [
'M/D/YY',
'D-MMM-YY',
'D-MMM',
'MMM-YY',
'h:mm AM/PM',
'h:mm:ss AM/PM',
'h:mm',
'h:mm:ss',
'M/D/YY h:mm',
'mm:ss',
'[h]:mm:ss',
'mm:ss.0',
]
i = 1
for format in formats:
style = xlwt.XFStyle()
style.num_format_str = format
sheet.write(i, 0, format)
sheet.write(i, 1, datetime.now(), style)
i += 1
workbook.save('datetime-formats.xls')
Run the program.
python datetime-format.py
The output Excel file.
Happy Coding 😊