You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何仅移除日期输出中的时间部分?

解决方案

方法1:直接处理最终输出字符串

针对你当前print(trh)得到的September 16, 2022, 11:31 pm 20 Days格式,通过字符串分割重组就能快速得到目标格式:

# 假设trh是当前输出的字符串
trh = "September 16, 2022, 11:31 pm 20 Days"

# 提取日期部分(截取到第二个逗号前)
date_part = ', '.join(trh.split(',')[:2]).strip()
# 提取天数部分(取最后两个元素拼接)
days_part = ' '.join(trh.split()[-2:])
# 重组为目标格式
formatted_trh = f"{date_part} ({days_part})"

print(formatted_trh)  # 输出: September 16, 2022 (20 Days)

方法2:在生成trh时直接构建目标格式

看你的第二部分代码,在拼接trh=trh+' '+DaysRemain前,trh是包含时间的原始日期字符串,可在此步骤直接清理时间并构建格式:

else:
    try:
        trh = data.split('phone":"')[1].split('"')[0]
        if trh.lower()[:2] == 'un':
            DaysRemain = " Days"
            formatted_trh = f"{trh} ({DaysRemain})"
        else:
            # 清理时间部分:截取到第二个逗号前
            clean_date = ', '.join(trh.split(',')[:2]).strip()
            DaysRemain = f"{str(tarih_clear(trh))} Days"
            # 直接生成目标格式
            formatted_trh = f"{clean_date} ({DaysRemain})"
        # 替换原trh为格式化后的字符串
        trh = formatted_trh
    except:
        pass

补充适配方案

如果日期字符串的时间位置有变动,可通过识别am/pm来截断:

# 另一种清理时间的逻辑
if 'pm' in trh:
    clean_date = trh.split('pm')[0].strip().rstrip(',')
elif 'am' in trh:
    clean_date = trh.split('am')[0].strip().rstrip(',')

内容的提问来源于stack exchange,提问作者Troy9090

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 17:05:41