python实现将中文日期转换为数字日期
作者:Huang supreme 时间:2023-07-10 10:39:33
1、说明
这篇文章是帮一个群友解答的问题。
他有一个需求,就是对于日期的录入都是中文形式的,需要转换为数字形式的。由于python库中没有函数直接进行转换,因此我写了本篇文章。
2、测试源数据如下
3、代码如下
df = pd.read_excel(r"C:\Users\黄伟\Desktop\chinese_english.xlsx")
display(df)
def func(x):
year = x.split("年")[0]
month = x.split("年")[1].split("月")[0]
day = x.split("年")[1].split("月")[1].split("日")[0]
if len(day) >= 3:
day = day[0] + day[2]
chinese_english = dict(零=0,一=1,二=2,三=3,四=4,五=5,六=6,七=7,八=8,九=9,十=10)
year = "".join(str(chinese_english[i]) for i in year)
month = "".join(str(chinese_english[i]) for i in month)
day = "".join(str(chinese_english[i]) for i in day)
if len(month) == 3:
month = month[0] + month[2]
if len(day) == 3:
day = day[0] + day[2]
final_date = year + "." + month + "." + day
return final_date
df["final_date"] = df["日期"].apply(func)
display(df)
结果如下:
补充知识:python 格式化时间含中文报错
报错内容
UnicodeEncodeError: 'locale' codec can't encode character '\u5e74' in position 2: Illegal byte sequence:
word = (datetime.today() + timedelta(days=keyDate.get(k, 0))).strftime('%Y年%m月%d日')
将上述代码更改为:
word = (datetime.today() + timedelta(days=keyDate.get(k, 0))).strftime('%Y{y}%m{m}%d{d}').format(y='年',m='月',d='日')
即可。
来源:https://blog.csdn.net/weixin_41261833/article/details/104265937
标签:python,中文,转换,数字
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python实现扫雷游戏的示例
2023-04-14 12:07:21
![](https://img.aspxhome.com/file/2023/6/84976_0s.png)
python apscheduler cron定时任务触发接口自动化巡检过程
2023-01-04 19:52:50
![](https://img.aspxhome.com/file/2023/2/111972_0s.jpg)
为MySQL创建高性能索引
2024-01-19 09:22:32
![](https://img.aspxhome.com/file/2023/7/93057_0s.jpg)
Tab(选项卡)的产品设计原则及应用[译]
2009-07-09 19:05:00
![](https://img.aspxhome.com/file/UploadPic/20097/9/01-24s.gif)
Pytorch maxpool的ceil_mode用法
2023-03-20 13:28:05
golang的协程上下文的具体使用
2024-02-01 00:41:02
asp如何制作一个简单的翻页程序?
2010-06-29 21:26:00
vue项目中如何引入cesium
2024-05-28 15:52:29
![](https://img.aspxhome.com/file/2023/3/123153_0s.png)
将pandas.dataframe的数据写入到文件中的方法
2022-07-13 14:56:38
![](https://img.aspxhome.com/file/2023/1/77791_0s.jpg)
PDO::commit讲解
2023-06-14 05:35:45
Python获取时间戳代码实例
2023-11-13 04:02:52
SQL Server Alert发送告警邮件少了的原因
2024-01-27 14:15:38
![](https://img.aspxhome.com/file/2023/7/94467_0s.png)
MySQL数据库单一表突破4G限制的实现方法
2008-11-02 14:43:00
python可视化分析绘制带趋势线的散点图和边缘直方图
2023-08-16 04:10:10
![](https://img.aspxhome.com/file/2023/0/77900_0s.png)
python基础之编码规范总结
2021-04-17 06:13:26
vs code开发中语法正确但显示报错问题分析解决
2023-08-05 11:54:26
![](https://img.aspxhome.com/file/2023/7/132427_0s.png)
python数字图像处理环境安装与配置过程示例
2023-03-05 07:00:25
![](https://img.aspxhome.com/file/2023/0/110290_0s.png)
python定时截屏实现
2021-01-28 22:04:09
![](https://img.aspxhome.com/file/2023/6/86206_0s.jpg)
python numpy 一维数组转变为多维数组的实例
2023-03-19 23:30:10
![](https://img.aspxhome.com/file/2023/0/90370_0s.jpg)
asp一个空间绑定N个域名的方法!
2009-03-08 18:32:00