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,, style)

The following example Python program will show you how to write Excel file with different date time format cells.

import xlwt
from datetime import datetime

workbook = xlwt.Workbook()
sheet = workbook.add_sheet("Formats")

header_font = xlwt.Font() = '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 = [
    'h:mm AM/PM',
    'h:mm:ss AM/PM',
    'M/D/YY h:mm',

i = 1
for format in formats:
    style = xlwt.XFStyle()
    style.num_format_str = format
    sheet.write(i, 0, format)
    sheet.write(i, 1,, style)
    i += 1'datetime-formats.xls')

Run the program.


The output Excel file.

Python xlwt with Date Time Formats for Excel Cells

Happy Coding 😊