Python——20多行代码教你将系统时间储存到Excel里

这是Python做Excel处理的小白必备的技能,接下来我用20多行代码将它呈现出来

代码如下↓

我没有写注释的好习惯,大家勿喷哈!你们以后写代码最好写注释!

from datetime import datetime
from openpyxl.styles import *
import openpyxl

excel = openpyxl.load_workbook("Dates.xlsx")
excel.create_sheet("Date Time")
excel_sheet = excel.active
dates = {
    "Year": datetime.now().year,
    "Month": datetime.now().month,
    "Day": datetime.now().day,
    "Hour": datetime.now().hour,
    "Minute": datetime.now().minute,
    "Second": datetime.now().second,
}
for dates_name, date_time in dates.items():
    excel_sheet.append([dates_name, date_time])
for i in range(1, 7):
    excel_sheet["A" + str(i)].font = Font(name='Times New Roman', size=16, bold=True, italic=True, color=colors.BLACK)
for i in range(1, 7):
    excel_sheet["B" + str(i)].font = Font(name='Times New Roman', size=14, bold=True, italic=True, color=colors.BLUE)
excel.save("Dates.xlsx")

这还是我用pep8格式写的!!!

代码分析:

导入对应库,openpyxl库自己pip,这个库是写Excel必备的。

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple openpyxl
# datetime库是为了读取系统时间。
from datetime import datetime
# openpyxl是操控Excel专用的。
from openpyxl.styles import *
import openpyxl

Excel自己新建一个,不做任何操作,命名为Dates.xlsx。

# load_work()函数导入Excel文件。
excel = openpyxl.load_workbook("Dates.xlsx")
# 新建一个sheet。
excel.create_sheet("Date Time")
# 激活work sheet。
excel_sheet = excel.active

下面的代码我就不用多说了哈,将系统的年月日时分秒用字典储存下来。

# 如果想让时间跟精准的话可以将datetime.now().second前面加个float()函数。
dates = {
    "Year": datetime.now().year,
    "Month": datetime.now().month,
    "Day": datetime.now().day,
    "Hour": datetime.now().hour,
    "Minute": datetime.now().minute,
    "Second": datetime.now().second,
}

下面的代码至关重要这是将时间储存到Excel文件的代码。

# 将日期时间写入单元格,一个列表一行。
for dates_name, date_time in dates.items():
    excel_sheet.append([dates_name, date_time])
# 设置单元格字体样式。
for i in range(1, 7):
    excel_sheet["A" + str(i)].font = Font(name='Times New Roman', size=16, bold=True, italic=True, color=colors.BLACK)
for i in range(1, 7):
    excel_sheet["B" + str(i)].font = Font(name='Times New Roman', size=14, bold=True, italic=True, color=colors.BLUE)
# 保存文件。
excel.save("Dates.xlsx")

你学废了吗?是不是很简单?

噢耶
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 20个属于我常用工具的Python库 Requests.Kenneth Reitz写的最富盛名的http库。每个P...
    飞吧_5966阅读 7,126评论 0 1
  • GitHub 上有一个 Awesome - XXX 系列的资源整理,资源非常丰富,涉及面非常广。awesome-p...
    若与阅读 19,126评论 4 418
  • 久违的晴天,家长会。 家长大会开好到教室时,离放学已经没多少时间了。班主任说已经安排了三个家长分享经验。 放学铃声...
    飘雪儿5阅读 12,232评论 16 22
  • 创业是很多人的梦想,多少人为了理想和不甘选择了创业来实现自我价值,我就是其中一个。 创业后,我由女人变成了超人,什...
    亦宝宝阅读 5,865评论 4 1
  • 今天感恩节哎,感谢一直在我身边的亲朋好友。感恩相遇!感恩不离不弃。 中午开了第一次的党会,身份的转变要...
    余生动听阅读 13,601评论 0 11

友情链接更多精彩内容