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

如何从URL末尾部分提取日期戳用于后续日期格式处理?

从URL末尾提取日期后缀的解决方案

Hey JC, 这里有几种简单可靠的方法帮你从给定URL的末尾提取目标日期字符串(比如示例中的092520):

方法1:字符串分割法(适合结构固定的URL)

如果你的URL始终是以-分隔内容,且日期部分是最后一段,直接按-分割字符串后取最后一个元素就行,这种方法简单高效。

Python 实现:

url = "/news/this-super-chic-paris-hotel-is-hosting-dinners-in-its-swimming-pool-092520"
date_part = url.split('-')[-1]
print(date_part)  # 输出: 092520

JavaScript 实现:

const url = "/news/this-super-chic-paris-hotel-is-hosting-dinners-in-its-swimming-pool-092520";
const datePart = url.split('-').pop();
console.log(datePart); // 输出: 092520

方法2:正则表达式法(适合结构灵活的URL)

如果URL的结构偶尔有变化,但日期部分始终是末尾的数字序列,用正则匹配末尾的数字会更灵活,能适应更多场景。

Python 实现:

import re
url = "/news/this-super-chic-paris-hotel-is-hosting-dinners-in-its-swimming-pool-092520"
match = re.search(r'\d+$', url)  # \d+匹配1个或多个数字,$标记字符串结尾
if match:
    date_part = match.group()
    print(date_part)  # 输出: 092520

JavaScript 实现:

const url = "/news/this-super-chic-paris-hotel-is-hosting-dinners-in-its-swimming-pool-092520";
const regex = /\d+$/;
const match = url.match(regex);
if (match) {
    const datePart = match[0];
    console.log(datePart); // 输出: 092520
}

额外小提示:处理带参数的URL

如果URL末尾带有查询参数(比如/news/xxx-092520?param=1),可以先去掉参数部分再提取:

Python 示例:

url_with_params = "/news/this-super-chic-paris-hotel-is-hosting-dinners-in-its-swimming-pool-092520?param=1"
clean_url = url_with_params.split('?')[0]  # 移除参数部分
date_part = clean_url.split('-')[-1]
print(date_part)  # 输出: 092520

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 09:42:47