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

Python中无法用format函数格式化NSE历史数据链接求助

解决Python格式化NSE印度历史数据URL的问题

嘿,这事儿没你想的复杂!你只需要用Python的字符串格式化工具,把URL里的年份、月份和日期按NSE的要求填充好就行,我给你一步步说明怎么弄:

首先得明确NSE这个URL的格式规则:

  • 年份是四位数字(比如2024)
  • 月份是三位大写的英文缩写(比如JAN、FEB、MAR),不管是路径里还是文件名里的月份都得是这个格式
  • 日期是两位数字(补前导零,比如01、15、31)

下面是两种实用的实现方式:

方法1:使用str.format()函数

这是比较经典的字符串格式化方式,适合需要复用模板的场景:

import webbrowser
from datetime import datetime

# 方式一:手动指定目标日期
# year = "2024"
# month_abbr = "JAN"
# date_str = "01"

# 方式二:用datetime自动生成格式(更推荐,避免手动输入出错)
target_date = datetime(2024, 1, 1)
year = target_date.strftime("%Y")  # 提取四位年份
month_abbr = target_date.strftime("%b").upper()  # 转大写的三位月份缩写
date_str = target_date.strftime("%d")  # 提取两位日期

# 格式化URL模板
url_template = "https://www.nseindia.com/content/historical/EQUITIES/{year}/{month}/cm{date}{month}{year}bhav.csv.zip"
final_url = url_template.format(year=year, month=month_abbr, date=date_str)

# 打开链接
webbrowser.open(final_url)

方法2:使用f-string(Python 3.6+)

如果你的Python版本在3.6以上,f-string会更简洁直观:

import webbrowser
from datetime import datetime

target_date = datetime(2024, 3, 15)
year = target_date.strftime("%Y")
month_abbr = target_date.strftime("%b").upper()
date_str = target_date.strftime("%d")

# 直接用f-string插入变量
final_url = f"https://www.nseindia.com/content/historical/EQUITIES/{year}/{month_abbr}/cm{date_str}{month_abbr}{year}bhav.csv.zip"
webbrowser.open(final_url)

关键注意事项

  • 一定要保证月份是大写的三位缩写,比如JAN而不是jan或者01,否则NSE的服务器会找不到对应的文件
  • 日期必须是两位数字,比如1号要写成01而不是1,strftime("%d")会自动帮你补前导零
  • 如果手动输入日期参数,要严格匹配格式,不然生成的URL会无效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 20:23:14