Python-批量日期数据格式化处理

日期格式化处理小程序

背景

用于批量格式化数据,背景就是领导给我我一张下面这样的表格,其中启用日期是五花八门的格式,大概有几万行,需要把启用日期一列统一格式化为“YYYY-MM-DD”的格式,显然,针对这种格式不统一的数据,用Excel处理很费劲。

生产厂家启用日期
赛默飞2021.12.28
赛默飞20190515
赛默飞2013/3/30
赛默飞2011-3
安捷伦2012.8.10
安捷伦2015.02.09
安捷伦2020/10/1
安捷伦20200708

初步解决方案

让AI处理,结果AI处理了几百行后告诉我太多了,它不干了,我再问就直接丢给我一段Python代码,果断引入依赖,稍微调了调,勉强能够完成工作。

import pandas as pd
from datetime import datetime

# 读取Excel文件
input_file = 'C:\\Users\\Aerle\\Desktop\\日期数据.xlsx'  # 假设您的Excel文件名是input.xlsx
output_file = 'C:\\Users\\Aerle\\Desktop\\格式化后的结果.xlsx'  # 转换后的数据将保存到这个文件中
df = pd.read_excel(input_file, header=None)  # 假设数据在第一个工作表,且没有列标题

# 定义一个函数来解析和格式化日期
def format_date(date_str):
    # 尝试多种可能的日期格式来解析字符串
    formats = ['%Y%m%d', '%Y.%m.%d', '%Y/%m/%d', '%Y-%m', '%Y/%m/%d','%Y.%m','%Y-%m-%d']
    for fmt in formats:
        try:
            # 解析日期字符串
            date = datetime.strptime(date_str, fmt)
            # 格式化为YYYY-MM-dd
            return date.strftime('%Y-%m-%d')
        except ValueError:
            pass  # 如果当前格式不匹配,则尝试下一个格式
    return None  # 如果所有格式都不匹配,则返回None

# 应用函数到数据列的每一个元素
df[0] = df[0].apply(format_date)

# 将结果输出到一个新的Excel工作表中
df.to_excel(output_file, index=False, header=False)  # 不包含索引和列标题

实现GUI操作

但是很明显,文件名跟输出路径都需要在代码中修改,很不友好,决定给这段代码加上简单的GUI,通过不断的调试,最终完成如下代码,以下代码可以直接运行:

import os
import subprocess
import tkinter as tk
from tkinter import filedialog
import pandas as pd
from datetime import datetime

def select_input_file(root,input_file_path_var):
    input_file_path = filedialog.askopenfilename(filetypes=[("Excel files", "*.xlsx;*.xls")])
    if input_file_path:
        input_file_path_var.delete(0, tk.END)
        input_file_path_var.insert(0, input_file_path)
        return input_file_path

def select_output_file(root,output_file_path_var):
    output_file_path = filedialog.asksaveasfilename(defaultextension=".xlsx")
    if output_file_path:
        output_file_path_var.delete(0,tk.END)
        output_file_path_var.insert(0, output_file_path)
        return output_file_path

# 定义一个函数来解析和格式化日期
def format_date(date_str):
    # 尝试多种可能的日期格式来解析字符串
    formats = ['%Y%m%d', '%Y.%m.%d', '%Y/%m/%d', '%Y-%m', '%Y/%m/%d','%Y.%m','%Y-%m-%d']
    for fmt in formats:
        try:
            # 解析日期字符串
            date = datetime.strptime(date_str, fmt)
            # 格式化为YYYY-MM-dd
            return date.strftime('%Y-%m-%d')
        except ValueError:
            pass  # 如果当前格式不匹配,则尝试下一个格式
    return None  # 如果所有格式都不匹配,则返回None

# 定义要执行的主要脚本
def do_format(root, input_file_path_var,output_file_path_var):
    inputfile = input_file_path_var.get()
    outputfile = output_file_path_var.get()
    df = pd.read_excel(inputfile, header=None)  # 假设数据在第一个工作表,且没有列标题
    # 应用函数到数据列的每一个元素
    df[0] = df[0].apply(format_date)
    # 将结果输出到一个新的Excel工作表中
    df.to_excel(outputfile, index=False, header=False)  # 不包含索引和列标题
    root.destroy()
# 创建主函数
def main():
    # 创建主窗口
    root = tk.Tk()
    root.title("日期格式化小工具")
    # 创建一个Tkinter变量来存储文件路径
    input_file_path_var = tk.StringVar()
    output_file_path_var = tk.StringVar()
    # 输入文件框
    input_frame = tk.Frame(root)
    input_frame.pack(pady=10)
    input_label = tk.Label(input_frame, text="输入文件:")
    input_label.pack(side=tk.LEFT)
    input_file_path_var = tk.Entry(input_frame, width=50)
    input_file_path_var.pack(side=tk.LEFT)
    input_button = tk.Button(input_frame, text="选择文件", command=lambda:select_input_file(root,input_file_path_var))
    input_button.pack(side=tk.LEFT)
    # 输出文件框
    output_frame = tk.Frame(root)
    output_frame.pack(pady=10)
    output_label = tk.Label(output_frame, text="输出文件:")
    output_label.pack(side=tk.LEFT)
    output_file_path_var = tk.Entry(output_frame, width=50)
    output_file_path_var.pack(side=tk.LEFT)
    output_button = tk.Button(output_frame, text="选择路径", command=lambda:select_output_file(root,output_file_path_var))
    output_button.pack(side=tk.LEFT)
    # 创建按钮用于执行脚本
    execute_button = tk.Button(root, text="执行脚本", command=lambda:do_format(root, input_file_path_var,output_file_path_var))
    execute_button.pack(pady=5)
    # 运行Tkinter事件循环
    root.mainloop()
if __name__ == "__main__":
    main()

Pyinstaller打包

对上面完成的脚本进行打包成EXE可执行文件给同事们用,使用pytinstaller进行,只需要一行代码:

PS D:\VSCode-workspace\Python> cd .\Usefull_Utils\
PS D:\VSCode-workspace\Python\Usefull_Utils> pip3.12 install --upgrade pyinstaller
PS D:\VSCode-workspace\Python\Usefull_Utils> pyinstaller .\dateFormatter2.0.py

项目地址

https://gitcode.com/weixin_44803446/UsefulPythonUtils/overview

  • 12
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凉拌糖醋鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值