简体   繁体   English

关于使用 python 将字符串导出为日期的 xlsxWriter 问题

[英]xlsxWriter issue regarding exporting String as dates using python

I have a list that includes dates in the following format: 11/01/2019.我有一个列表,其中包含以下格式的日期:2019 年 11 月 1 日。 This date i convert to string.When I export this list to Excel, The Excel sheet recognizes these string as date.Is there a way to make these dates recognizable by Excel as string using pyhton?thank a lot.我将此日期转换为字符串。当我将此列表导出到 Excel 时,Excel 工作表将这些字符串识别为日期。有没有办法使用 ZC1D81AF5835844B4E9D936910DEDthan8 字符串使这些日期被 ZC1D81AF5835844B4E9D936910DEDthan8 识别

DateTable日期表
11/01/2019 2019 年 11 月 1 日
12/01/2019 2019 年 12 月 1 日
13/01/2019 13/01/2019
data.insert(0, {'Date':datetime.strptime(str(DateTable)[j]),'%d/%m/%Y').strftime('%d/%m/%Y')})
self.date.to_excel('date.xlsx', sheet_name = 'Sheet1', index=False, engine='xlsxwriter') 

To understand what's at stake read The Spanish family wrongly accused of child pornography due to a mistake reading a date .要了解危在旦夕,请阅读西班牙家庭因阅读日期错误而被错误指控儿童色情内容

From the comments it looks like the real question is how to generate an Excel file that gets imported into another appplication.从评论看来,真正的问题是如何生成导入另一个应用程序的 Excel 文件。 Don't convert dates to strings, especially in this case .不要将日期转换为字符串,尤其是在这种情况下

If you want to display dates in a certain way, specify the date display format when creating the ExcelWriter object:如果要以某种方式显示日期,请在创建ExcelWriter object 时指定日期显示格式:

writer = pd.ExcelWriter("pandas_datetime.xlsx",
                        engine='xlsxwriter',
                        datetime_format='dd/mm/yyyy hh:mm:ss',
                        date_format='dd/mm/yyyy')

Excel files aren't text, and all libraries that can import Excel files can handle date values, or know to read the formatted text value of a number or date. Excel 文件不是文本,所有可以导入 Excel 文件的库都可以处理日期值,或者知道读取数字或日期的格式化文本值。

Applications can import Excel dates without problems.应用程序可以毫无问题地导入 Excel 日期。 That's the one advantage Excel has over CSV files - numbers and dates are binary values, they don't need parsing and aren't affected by localization settings.这是 Excel 优于 CSV 文件的一个优势 - 数字和日期是二进制值,它们不需要解析并且不受本地化设置的影响。

If an application has to work with text though, it's always possible that the wrong format will be used, eg because the machine's locale settings changed, because whoever generated the Excel sheet made a mistake, because the application has to import files from multiple other systems that use different formats.但是,如果应用程序必须使用文本,则总是可能使用错误的格式,例如因为机器的区域设置更改了,因为生成 Excel 表的人犯了错误,因为应用程序必须从多个其他系统导入文件使用不同的格式。

Explanation解释

Dates in Python (and C#, Java, JavaScript, MySQL, PostgreSQL,....) have no format. Dates in Python (and C#, Java, JavaScript, MySQL, PostgreSQL,....) have no format. They're binary types.它们是二进制类型。 Formats apply only when parsing strings into dates or formatting dates as strings for export or display.格式仅适用于将字符串解析为日期或将日期格式化为字符串以供导出或显示。

Excel has a date type as well. Excel 也有一个日期类型。 Dates and numbers aren't stored as strings, they're stored as binary values.日期和数字不存储为字符串,它们存储为二进制值。 How they are displayed depends on the cell's number format.它们的显示方式取决于单元格的数字格式。 Dates are stored as an OADate decimal whose integer part is an offset from 1899-12-30 and fractional part is the time in a 24 hour period.日期存储为 OADate 十进制,其 integer 部分是从 1899-12-30 的偏移量,小数部分是 24 小时内的时间。

If you want to display dates in a specific format, specify it in the cell style.如果要以特定格式显示日期,请在单元格样式中指定它。

The XlsxWriter docs explain how to do that in Working with dates and time . XlsxWriter 文档在Working with dates and time中解释了如何做到这一点。 The examples actually use the format you want:这些示例实际上使用了您想要的格式:

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

# Widen column A for extra visibility.
worksheet.set_column('A:A', 30)

# A number to convert to a date.
number = 41333.5

# Write it as a number without formatting.
worksheet.write('A1', number)                # 41333.5

format2 = workbook.add_format({'num_format': 'dd/mm/yy'})
worksheet.write('A2', number, format2)       # 28/02/13

format3 = workbook.add_format({'num_format': 'mm/dd/yy'})
worksheet.write('A3', number, format3)       # 02/28/13

You don't have to convert the date to an OADate decimal though.不过,您不必将日期转换为 OADate 小数。 You can store dates directly.您可以直接存储日期。 XlsxWriter: XlsxWriter:

... supports datetime objects of type datetime.datetime, datetime.date, datetime.time and datetime.timedelta. ... 支持 datetime.datetime、datetime.date、datetime.time 和 datetime.timedelta 类型的 datetime 对象。

The XlsxWriter docs show how to work with dates in Pandas as well . XlsxWriter 文档还展示了如何 使用 Pandas 中的日期 It's even easier - just pass the desired format as a parameter:它更容易 - 只需将所需的格式作为参数传递:

import pandas as pd
from datetime import datetime, date

# Create a Pandas dataframe from some datetime data.
df = pd.DataFrame({'Date and time': [datetime(2015, 1, 1, 11, 30, 55),
                                     datetime(2015, 1, 2, 1,  20, 33),
                                     datetime(2015, 1, 3, 11, 10    ),
                                     datetime(2015, 1, 4, 16, 45, 35),
                                     datetime(2015, 1, 5, 12, 10, 15)],
                   'Dates only':    [date(2015, 2, 1),
                                     date(2015, 2, 2),
                                     date(2015, 2, 3),
                                     date(2015, 2, 4),
                                     date(2015, 2, 5)],
                   })

# Create a Pandas Excel writer using XlsxWriter as the engine.
# Also set the default datetime and date formats.
writer = pd.ExcelWriter("pandas_datetime.xlsx",
                        engine='xlsxwriter',
                        datetime_format='dd/mm/yyyy hh:mm:ss',
                        date_format='dd/mm/yyyy')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

...
# Close the Pandas Excel writer and output the Excel file.
writer.save()

You need to set number format of the cell to "Plain Text", which is {'num_format': '@'}您需要将单元格的数字格式设置为“纯文本”,即{'num_format': '@'}

workbook = Workbook("output.xlsx")
cell_format = workbook.add_format({'num_format': '@'})
worksheet = workbook.add_worksheet()
worksheet.write(0, 0, "15/12/2021", cell_format)
workbook.close()

And with pandas:并使用 pandas:

writer = pd.ExcelWriter("output.xlsx")
df.to_excel(writer, 'Sheet1')
workbook = writer.book
worksheet = writer.sheets['Sheet1']
cell_format = workbook.add_format({"num_format": "@"})
worksheet.set_column('A', 1, cell_format)
writer.save()

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

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