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

Python实现URL分割:提取末尾6字符及日期格式转换

Python提取URL末尾6字符及日期格式转换

提取URL末尾6个字符

针对你提到的非标准URL(有时以-221104或--221104结尾),有两种常用处理方式:

  • 直接切片提取:如果确定目标6字符是URL的最后6位,直接用字符串切片即可:
url = "/es/ideas-de-trading-y-noticias/el-ibex-35-insiste-en-buscar-los-7900-puntos-a-la-espera-de-las--221104"
target_chars = url[-6:]
print(target_chars)  # 输出: 221104
  • 正则匹配提取:如果URL结尾可能带额外符号,但目标是最后6个数字,用正则表达式精准匹配:
import re

url = "/es/ideas-de-trading-y-noticias/el-ibex-35-insiste-en-buscar-los-7900-puntos-a-la-espera-de-las--221104"
match_result = re.search(r'\d{6}$', url)
if match_result:
    target_chars = match_result.group()
    print(target_chars)  # 输出: 221104

转换为指定日期格式

使用Python内置的datetime模块可以快速完成格式转换:

from datetime import datetime

date_str = "221104"
# 解析字符串为日期对象,%y代表两位年份,%m代表两位月份,%d代表两位日期
date_obj = datetime.strptime(date_str, "%y%m%d")
# 格式化为"日 月 年"的形式
formatted_date = date_obj.strftime("%d %m %Y")
print(formatted_date)  # 输出: 04 11 2022

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:15:35