python - How to format cell with datetime object of the form 'yyyy-mm-dd hh:mm:ss' in Excel using openpyxl

Python - How to format cell with datetime object of the form 'yyyy-mm-dd hh:mm:ss' in Excel using openpyxl

To format a cell with a datetime object in Excel using openpyxl, you need to use the number_format attribute of the cell to set the desired date-time format. The format string 'yyyy-mm-dd hh:mm:ss' can be directly used to achieve this.

Here is an example of how you can do this:

  1. Install openpyxl if you haven't already:

    pip install openpyxl 
  2. Use the following script to create an Excel file and format the cells with datetime objects in the specified format:

    from openpyxl import Workbook from openpyxl.styles import NamedStyle from datetime import datetime # Create a new workbook and select the active worksheet wb = Workbook() ws = wb.active # Create a NamedStyle for the datetime format date_style = NamedStyle(name="datetime_style", number_format='yyyy-mm-dd hh:mm:ss') # Register the style with the workbook wb.add_named_style(date_style) # Example datetime object dt = datetime(2023, 5, 23, 14, 30, 45) # Assign the datetime object to a cell cell = ws['A1'] cell.value = dt # Apply the datetime style to the cell cell.style = date_style # Save the workbook to a file wb.save("datetime_example.xlsx") 

Explanation

  1. Install openpyxl: The openpyxl library is used for reading and writing Excel files in Python.

  2. Create a Workbook and Worksheet:

    wb = Workbook() ws = wb.active 
  3. Create and Register the NamedStyle:

    date_style = NamedStyle(name="datetime_style", number_format='yyyy-mm-dd hh:mm:ss') wb.add_named_style(date_style) 
    • NamedStyle is used to create a reusable style with the specified date-time format.
    • number_format='yyyy-mm-dd hh:mm:ss' specifies the desired format for the datetime.
  4. Assign a datetime Object to a Cell:

    dt = datetime(2023, 5, 23, 14, 30, 45) cell = ws['A1'] cell.value = dt 
  5. Apply the Style to the Cell:

    cell.style = date_style 

    This sets the style of the cell to the previously defined datetime_style, which formats the cell content as yyyy-mm-dd hh:mm:ss.

  6. Save the Workbook:

    wb.save("datetime_example.xlsx") 

This script will create an Excel file named datetime_example.xlsx with the datetime object formatted as yyyy-mm-dd hh:mm:ss in cell A1.

Examples

  1. Basic DateTime Formatting in openpyxl

    Description: Set the number format of a cell to display datetime in the desired format.

    Code:

    import openpyxl from datetime import datetime wb = openpyxl.Workbook() ws = wb.active current_time = datetime.now() ws['A1'] = current_time ws['A1'].number_format = 'yyyy-mm-dd hh:mm:ss' wb.save('datetime_format.xlsx') 
  2. Using NamedStyle for Consistent Formatting

    Description: Create and apply a NamedStyle to ensure consistent datetime formatting across multiple cells.

    Code:

    from openpyxl import Workbook from openpyxl.styles import NamedStyle from datetime import datetime wb = Workbook() ws = wb.active date_style = NamedStyle(name="datetime_style", number_format='yyyy-mm-dd hh:mm:ss') wb.add_named_style(date_style) current_time = datetime.now() for i in range(1, 6): cell = ws.cell(row=i, column=1, value=current_time) cell.style = date_style wb.save('datetime_named_style.xlsx') 
  3. Formatting Existing DateTime Data

    Description: Format existing datetime data in an Excel file using openpyxl.

    Code:

    import openpyxl wb = openpyxl.load_workbook('existing_file.xlsx') ws = wb.active for row in ws.iter_rows(min_row=1, max_row=10, min_col=1, max_col=1): for cell in row: cell.number_format = 'yyyy-mm-dd hh:mm:ss' wb.save('existing_file_formatted.xlsx') 
  4. Conditional DateTime Formatting

    Description: Apply conditional formatting based on the datetime value.

    Code:

    import openpyxl from openpyxl.styles import NamedStyle from datetime import datetime wb = openpyxl.Workbook() ws = wb.active date_style = NamedStyle(name="datetime_style", number_format='yyyy-mm-dd hh:mm:ss') wb.add_named_style(date_style) current_time = datetime.now() past_time = datetime(2020, 1, 1, 12, 0, 0) ws['A1'] = current_time ws['A2'] = past_time for cell in ws['A']: if cell.value < datetime(2021, 1, 1): cell.style = date_style wb.save('conditional_datetime_format.xlsx') 
  5. Using iso_dates for ISO 8601 Format

    Description: Use the iso_dates flag in openpyxl for ISO 8601 datetime format.

    Code:

    import openpyxl from datetime import datetime wb = openpyxl.Workbook() wb.iso_dates = True ws = wb.active current_time = datetime.now() ws['A1'] = current_time wb.save('iso_dates_format.xlsx') 
  6. Combining Date and Time in a Single Cell

    Description: Combine date and time parts into a single datetime cell and format it.

    Code:

    from openpyxl import Workbook from datetime import date, time wb = Workbook() ws = wb.active dt = datetime.combine(date(2023, 5, 24), time(15, 30, 0)) ws['A1'] = dt ws['A1'].number_format = 'yyyy-mm-dd hh:mm:ss' wb.save('combined_datetime.xlsx') 
  7. Formatting Multiple DateTime Columns

    Description: Format multiple columns that contain datetime values.

    Code:

    import openpyxl from datetime import datetime wb = openpyxl.Workbook() ws = wb.active current_time = datetime.now() for i in range(1, 6): ws.cell(row=i, column=1, value=current_time) ws.cell(row=i, column=2, value=current_time) for col in ['A', 'B']: for cell in ws[col]: cell.number_format = 'yyyy-mm-dd hh:mm:ss' wb.save('multiple_columns_datetime.xlsx') 
  8. Setting Default DateTime Format for a Sheet

    Description: Set a default datetime format for an entire sheet.

    Code:

    import openpyxl from openpyxl.styles import NamedStyle from datetime import datetime wb = openpyxl.Workbook() ws = wb.active date_style = NamedStyle(name="datetime_style", number_format='yyyy-mm-dd hh:mm:ss') wb.add_named_style(date_style) ws.sheet_properties.defaultColWidth = 20 current_time = datetime.now() ws['A1'] = current_time ws['A1'].style = date_style wb.save('default_datetime_format.xlsx') 
  9. Applying DateTime Format to Specific Rows

    Description: Apply datetime format to specific rows based on a condition.

    Code:

    import openpyxl from datetime import datetime wb = openpyxl.Workbook() ws = wb.active current_time = datetime.now() for i in range(1, 11): ws.cell(row=i, column=1, value=current_time) for row in ws.iter_rows(min_row=1, max_row=5, min_col=1, max_col=1): for cell in row: cell.number_format = 'yyyy-mm-dd hh:mm:ss' wb.save('specific_rows_datetime.xlsx') 
  10. Custom DateTime Formatting Function

    Description: Create a function to apply a custom datetime format to cells.

    Code:

    import openpyxl from datetime import datetime def apply_datetime_format(ws, cell_range): for row in ws[cell_range]: for cell in row: cell.number_format = 'yyyy-mm-dd hh:mm:ss' wb = openpyxl.Workbook() ws = wb.active current_time = datetime.now() for i in range(1, 6): ws.cell(row=i, column=1, value=current_time) apply_datetime_format(ws, 'A1:A5') wb.save('custom_function_datetime.xlsx') 

More Tags

android-3.0-honeycomb nlp osx-mountain-lion r-car relative-path ibeacon insert-update sentiment-analysis css-shapes tcpclient

More Programming Questions

More Bio laboratory Calculators

More Mixtures and solutions Calculators

More Math Calculators

More Auto Calculators