Hướng dẫn pandas excelwriter date format not working - định dạng ngày của pandas excelwriter không hoạt động

Cần hướng dẫn về cách tôi có thể định dạng một giá trị theo định dạng ngày trong Pandas trước khi nó in ra giá trị thành Excel sheet.

Tôi chưa quen với Pandas và phải chỉnh sửa mã hiện có khi các giá trị được xuất vào Excel sheet. Sau khi một số tính toán có điều kiện/chức năng được thực hiện, giá trị sau đó được đầu ra thành Excel. Giá trị hiện tại của tôi dường như ở string format không phải là định dạng ngày thân thiện với Excel.

Đầu ra của giá trị trông như thế này:

Hướng dẫn pandas excelwriter date format not working - định dạng ngày của pandas excelwriter không hoạt động

Cần thiết để định dạng đầu ra theo định dạng ngày

Hướng dẫn pandas excelwriter date format not working - định dạng ngày của pandas excelwriter không hoạt động

Tôi đã thử các tùy chọn của strptime, nhưng theo hiểu biết của tôi, các giá trị này cũng sẽ cung cấp đầu ra ở định dạng chuỗi. Phần lạ là, tôi cũng không thể định dạng cột theo định dạng Excel cho đến nay bằng cách sử dụng tùy chọn định dạng Excel.

Cảm ơn bạn đã dành thời gian và sự giúp đỡ của bạn.

Mã của tôi là một cái gì đó như thế này:


def calculate(snumber,owner,reason):
    #some if conditions and then
    date11 = Date + relativedelta(months = 1)
    return date11.strftime('%d %b %Y')


df['date1'] = df.apply(lambda x: calculate(x['snumber'], x['owner'], x['reason']), axis=1)

Điều này có lẽ đơn giản như OpenPyXL trở thành công cụ mặc định mới nhưng không được cấu hình cho định dạng ngày.

Công cụ mặc định để viết không thay đổi - đó vẫn là XLSXWriter, nhưng trong trường hợp này bạn không có XLSXWriter nên nó sử dụng OpenPyXL. Nếu bạn cài đặt xlsxwriter, bạn sẽ thấy hành vi trước đó.

Đối với vấn đề - dường như là do những điều này (

##############################################################################
#
# An example of converting a Pandas dataframe with datetimes to an xlsx file
# with a default datetime and date format using Pandas and XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright 2013-2022, John McNamara, 
#

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='mmm d yyyy hh:mm:ss',
                        date_format='mmmm dd yyyy')

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

# Get the xlsxwriter workbook and worksheet objects. in order to set the column
# widths, to make the dates clearer.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Get the dimensions of the dataframe.
(max_row, max_col) = df.shape

# Set the column widths, to make the dates clearer.
worksheet.set_column(1, max_col, 20)

# Close the Pandas Excel writer and output the Excel file.
writer.save()
2,
##############################################################################
#
# An example of converting a Pandas dataframe with datetimes to an xlsx file
# with a default datetime and date format using Pandas and XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright 2013-2022, John McNamara, 
#

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='mmm d yyyy hh:mm:ss',
                        date_format='mmmm dd yyyy')

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

# Get the xlsxwriter workbook and worksheet objects. in order to set the column
# widths, to make the dates clearer.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Get the dimensions of the dataframe.
(max_row, max_col) = df.shape

# Set the column widths, to make the dates clearer.
worksheet.set_column(1, max_col, 20)

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

classopenpyxlwriter (excelwriter): OpenpyxlWriter(ExcelWriter):
engine="openpyxl" = "openpyxl"
ASSIPED_EXTENSIONS = (".xlsx", ".xlsm") = (".xlsx", ".xlsm")
def__init __ ( __init__(
bản thân,,
đường dẫn,,
Động cơ = Không,=None,
date_format = không có,=None,
datetime_format = none,=None,
Chế độ: str = "w",: str = "w",
Storage_Options: StorageOptions = none,: StorageOptions = None,
if_sheet_exists: str | none = none,: str | None = None,
Động cơ_kwargs: Dict [Str, Any] | none = none,: dict[str, Any] | None = None,
** kwargs,kwargs,
):
# Sử dụng mô -đun OpenPyXL làm người viết Excel.
fromopenpyxl.workbookimportWorkbook openpyxl.workbook import Workbook
Động cơ_kwargs = Combine_kwargs (động cơ_kwargs, kwargs) = combine_kwargs(engine_kwargs, kwargs)
Super () .__ init __ (().__init__(
đường dẫn,,
Động cơ = Không,=mode,
date_format = không có,=storage_options,
datetime_format = none,=if_sheet_exists,
Chế độ: str = "w",=engine_kwargs,
Storage_Options: StorageOptions = none,

if_sheet_exists: str | none = none,

##############################################################################
#
# An example of converting a Pandas dataframe with datetimes to an xlsx file
# with a default datetime and date format using Pandas and XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright 2013-2022, John McNamara, 
#

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='mmm d yyyy hh:mm:ss',
                        date_format='mmmm dd yyyy')

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

# Get the xlsxwriter workbook and worksheet objects. in order to set the column
# widths, to make the dates clearer.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Get the dimensions of the dataframe.
(max_row, max_col) = df.shape

# Set the column widths, to make the dates clearer.
worksheet.set_column(1, max_col, 20)

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