【问题标题】:Python: Put date and time in xls columnsPython:将日期和时间放在 xls 列中
【发布时间】:2020-03-07 14:03:36
【问题描述】:

我想将日期导出到 Excel 列

我有以下代码:

from xlsxwriter import Workbook
from pathlib import Path
from datetime import date
from datetime import time

#time
Second = 55
Hour = 10
Minute = 11
time_sum = time(Hour, Minute, Second)

#Date
day = 2
year = 2019
month = 11
Date_sum = date(year, month, day)
date = []
date.extend((Date_sum, time_sum))

#write in excel
workbook = Workbook('datetime.xlsx')
Report_Sheet = workbook.add_worksheet()
# Write the column headers.
Report_Sheet.write(0, 0, 'datetime')
# Write the column data.
Report_Sheet.write_column(1, 0, date)
workbook.close()

但我在 Excel 中得到了这个:

但我想要正确的格式(日期和时间),以便 Excel 中的值直接正确。

【问题讨论】:

    标签: python excel datetime xls


    【解决方案1】:

    为什么不使用 pandas 并使用 to_excel 函数:

    例如使用 CSV 文件:

    string,date,number
    a string,2/5/11 9:16am,1.0
    a string,3/5/11 10:44pm,2.0
    a string,4/22/11 12:07pm,3.0
    a string,4/22/11 12:10pm,4.0
    a string,4/29/11 11:59am,1.0
    a string,5/2/11 1:41pm,2.0
    a string,5/2/11 2:02pm,3.0
    a string,5/2/11 2:56pm,4.0
    a string,5/2/11 3:00pm,5.0
    a string,5/2/14 3:02pm,6.0
    a string,5/2/14 3:18pm,7.0
    

    这样读:

    b=pd.read_csv('b.dat')
    b['date']=pd.to_datetime(b['date'],format='%m/%d/%y %I:%M%p') #convert col to datetime
    

    你可以像这样保存到excel:

    b.to_excel('yourfile.xls')
    

    它保留了日期格式(使用 libre office calc 测试)。

    【讨论】:

      【解决方案2】:

      Excel 中的日期是具有格式的数字。目前你有数字但没有格式。

      要显示日期/时间,您可以添加如下格式:

      workbook = Workbook('datetime.xlsx')
      Report_Sheet = workbook.add_worksheet()
      
      # Make the first column wider for clarity.
      Report_Sheet.set_column(0, 0, 20)
      
      datetime_format = workbook.add_format({'num_format': 'dd/mm/yy hh:mm'})
      
      # Write the column headers.
      Report_Sheet.write(0, 0, 'datetime')
      # Write the column data.
      Report_Sheet.write_column(1, 0, date, datetime_format)
      workbook.close()
      
      

      输出:

      但是,您通常希望有一个单独的日期和时间格式,因此您可能需要这样的格式:

      workbook = Workbook('datetime.xlsx')
      Report_Sheet = workbook.add_worksheet()
      
      # Make the first column wider for clarity.
      Report_Sheet.set_column(0, 0, 20)
      
      date_format = workbook.add_format({'num_format': 'dd/mm/yy'})
      time_format = workbook.add_format({'num_format': 'hh:mm'})
      
      # Write the column headers.
      Report_Sheet.write(0, 0, 'datetime')
      # Write the column data.
      Report_Sheet.write(1, 0, Date_sum, date_format)
      Report_Sheet.write(2, 0, time_sum, time_format)
      workbook.close()
      
      

      输出:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-29
        • 1970-01-01
        • 2015-11-07
        • 2021-05-07
        • 2019-02-20
        • 2017-05-14
        • 1970-01-01
        相关资源
        最近更新 更多