简体   繁体   English

XlsxWriter撰写日期为数字

[英]XlsxWriter writing date as number

I am writing date to a file and i am using: 我正在将日期写入文件,并且正在使用:

date.strftime('%m/%d/%Y')

and i am writing date object to excel file: 我正在将日期对象写入Excel文件:

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

where formatter is aligning it in the middle and r is the object in the current loop. 其中formatter将其对齐在中间,而r是当前循环中的对象。

It shows like 10/28/2016 but i want it to be saved as a number value (like 42871 for example). 它显示像10/28/2016但我希望将其保存为数字值(例如42871 )。 Is there any way this to happen within code and not manually in excel? 有什么办法可以在代码内发生,而不是在excel中手动发生?

The number value in Excel is what I'm assuming as the days since epoch, which in this case is January 1st, 1900. Refer to here . 我假设Excel中的数值是从纪元以来的天数,在本例中是1900年1月1日。请参阅此处 However, in practice you would want to use Dec 30, 1899 to account for leap years. 但是,实际上,您可能希望使用1899年12月30日来计算to年。 All you have to do is run a diff check and then get the days from the epoch. 您所要做的就是运行差异检查,然后从时代开始。

Assuming your date is 10/28/2016: 假设您的日期是2016年10月28日:

>>> from datetime import date
>>> new_value = (date(2016,10,28) - date(1899,12,30)).days
42671

Therefore, before you write your rows, just do some upfront calculation: 因此,在编写行之前,只需进行一些前期计算即可:

new_value = (your_date_in_the_row - date(1899,12,30)).days

As explained in the XlsxWriter documentation on Working with Dates and Times a date in Excel is just a number with a format. 如有关使用日期和时间的XlsxWriter文档中所述,Excel中的日期只是具有格式的数字。 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             )

workbook.close()

Output: 输出:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM