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

使用Python和Pandas将周数转换为对应周一日期的技术求助

根据年和周数生成对应周的首个周一日期

可以通过pandas的日期解析功能直接实现需求,核心是利用ISO周格式的字符串构造并转换日期,具体代码如下:

import pandas as pd

# 初始化原始DataFrame
df = pd.DataFrame({
    'weeknum':[12,24,36,48,50],
    'year':[2023,2023,2023,2023,2023]
})

# 生成对应周的首个周一日期并格式化
df['weekDate'] = pd.to_datetime(
    df['year'].astype(str) + '-W' + df['weeknum'].astype(str).str.zfill(2) + '-1',
    format='%G-W%V-%u'
).dt.strftime('%Y-%m-%d')

print(df)

代码说明:

  • 构造ISO周格式字符串:将年份、补零为两位的周数,以及代表周一的-1拼接,形成类似2023-W12-1的格式
  • 解析日期:使用pd.to_datetime配合格式符%G-W%V-%u,其中%G对应ISO年份,%V对应ISO周数,%u对应星期几(1=周一)
  • 格式化输出:通过dt.strftime('%Y-%m-%d')将日期转换为指定的字符串格式

运行后输出结果:

weeknum  year    weekDate
0       12  2023  2023-03-20
1       24  2023  2023-06-12
2       36  2023  2023-09-11
3       48  2023  2023-11-27
4       50  2023  2023-12-11

内容的提问来源于stack exchange,提问作者Alexandra Morel-Fonteray

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 05:17:19