python 把2018年8月9号转换成 2018-08-09

def date_of_conversion(CH_time):
    if '年' and '月' and '日' in CH_time:
        if len(CH_time) == 9:
            CH_time = CH_time[:-4] + '0' + CH_time[-4:-2] + '0' + CH_time[-2:]
        return CH_time.replace('年', '-').replace('月', '-').replace('日', '')
    elif '年' and '月' in CH_time:
        if len(CH_time) == 7:
            CH_time = CH_time[:-2] + '0' + CH_time[-2:]

        return CH_time.replace('年', '-').replace('月', '')
    else:
        return CH_time

遇到一个对比的问题,从excel里面取出来显示的是 年月日 有点蒙圈,顺手写了一下 不支持 2018年09月1日 2018年9月01日

有兴趣可以帮我改一下 谢谢

 

今天 看了一下 发现 卧槽 以前写的什么东西,现在改进一下

def date_of_conversion(CH_time, time_type='month'):
    """把2018年8月9号转换成 2018-08-09"""
    # if '年' and '月' and '日' in CH_time:
    #     if len(CH_time) == 9:
    #         CH_time = CH_time[:-4] + '0' + CH_time[-4:-2] + '0' + CH_time[-2:]
    #     return CH_time.replace('年', '-').replace('月', '-').replace('日', '')
    # elif '年' and '月' in CH_time:
    #     if len(CH_time) == 7:
    #         CH_time = CH_time[:-2] + '0' + CH_time[-2:]
    #
    #     return CH_time.replace('年', '-').replace('月', '')
    # else:
    #     return CH_time
    year_info = CH_time.split('年')
    month_info = year_info[-1].split('月')
    day_info = month_info[-1].split('日')
    new_date = year_info[0] + '-' + month_info[0] + '-' + day_info[0]
    st = time.strptime(new_date, '%Y-%m-%d')
    update_date = time.strftime('%Y-%m-%d', st)
    if time_type == 'year':
        return update_date
    elif time_type == 'month':
        return update_date[:7]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值