Python对表格中“2013-10-1”日期格式处理

2023-12-21 13:07:15

EXCEL修改方法

在这里插入图片描述右击单元格格式在这里插入图片描述在日期中可以修改类型
在这里插入图片描述

Python字符串操作

如何获取下面这种呢?人力手动修改很耗时间。可以使用replace字符串替换方法
在这里插入图片描述

import pandas as pd
import csv
import openpyxl as op

def readDataFile(readPath):  # readPath: 数据文件的地址和文件名
    try:
        if (readPath[-4:] == ".csv"):
            dfFile = pd.read_csv(readPath, header=0, sep=",")  # 间隔符为逗号,首行为标题行
            # dfFile = pd.read_csv(filePath, header=None, sep=",")  # sep: 间隔符,无标题行
        elif (readPath[-4:] == ".xls") or (readPath[-5:] == ".xlsx"):  # sheet_name 默认为 0
            dfFile = pd.read_excel(readPath,header=0)  # 首行为标题行
            # dfFile = pd.read_excel(filePath, header=None)  # 无标题行
        elif (readPath[-4:] == ".dat"):  # sep: 间隔符,header:首行是否为标题行
            dfFile = pd.read_table(readPath, sep=" ", header=0)  # 间隔符为空格,首行为标题行
            # dfFile = pd.read_table(filePath,sep=",",header=None) # 间隔符为逗号,无标题行
        else:
            print("不支持的文件格式。")
    except Exception as e:
        print("读取数据文件失败:{}".format(str(e)))
        return
    return dfFile

df = readDataFile('大厂2.csv')
date = df['DAY']
print(date)
for i in range(len(date)):
    print(date[i])
    data = str(date[i]).replace('-','')
    print(data)
    tableAll = op.load_workbook('test.xlsx')
    table1 = tableAll['Sheet1']
    table1.cell(i + 1, 1, data)
    tableAll.save('test.xlsx')

代码中包括原始列的读入,然后将每一行日期数据修改为字符串类型,并替换-为空,再依次存入xlsx文件中。

总结

使用Python可以对EXCEL中重复性的劳动工作批量化处理,Python就是excel的拓展,只要是手动能操作的事都可以交给代码自动化处理更大的数据。

文章来源:https://blog.csdn.net/qq_43920838/article/details/135127277
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。