nephilimrising nephilimrising - 11 months ago 63
Python Question

XlsxWriter writing date as number

I am writing date to a file and i am using:


and i am writing date object to excel file:

worksheet.write(row_count, column_count, r, formatter)

is aligning it in the middle and
is the object in the current loop.

It shows like
but i want it to be saved as a number value (like
for example). Is there any way this to happen within code and not manually in excel?

Answer Source

As explained in the XlsxWriter documentation on Working with Dates and Times a date in Excel is just a number with a format. If you omit the format you get the number:

from datetime import datetime
import xlsxwriter

workbook = xlsxwriter.Workbook('datetimes.xlsx')
worksheet = workbook.add_worksheet()

# Widen the first column so that the dates are visible.
worksheet.set_column('A:A', 20)

# Create a datetime object.
date_time = datetime.strptime('2017-05-16', '%Y-%m-%d')

# Create a format for the date or time.
date_format = workbook.add_format({'num_format': 'd mmmm yyyy'})

worksheet.write('A1', date_time, date_format)
worksheet.write('A2', date_time             )



enter image description here