gpt4 book ai didi

python实现将中文日期转换为数字日期

转载 作者:qq735679552 更新时间:2022-09-29 22:32:09 26 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章python实现将中文日期转换为数字日期由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

1、说明 。

这篇文章是帮一个群友解答的问题.

他有一个需求,就是对于日期的录入都是中文形式的,需要转换为数字形式的。由于python库中没有函数直接进行转换,因此我写了本篇文章.

2、测试源数据如下 。

python实现将中文日期转换为数字日期

3、代码如下 。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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实现将中文日期转换为数字日期

补充知识: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日') 。

python实现将中文日期转换为数字日期

将上述代码更改为:

word = (datetime.today() + timedelta(days=keyDate.get(k, 0))).strftime('%Y{y}%m{m}%d{d}').format(y='年',m='月',d='日') 。

即可.

以上这篇python实现将中文日期转换为数字日期就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我.

原文链接:https://blog.csdn.net/weixin_41261833/article/details/104265937 。

最后此篇关于python实现将中文日期转换为数字日期的文章就讲到这里了,如果你想了解更多关于python实现将中文日期转换为数字日期的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com