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

如何在Python中从指定格式的时间戳提取周数?

Python脚本提取时间戳对应的周数

没问题,我来帮你搞定这个需求!针对你给出的时间戳格式,我们可以用Python的datetime模块轻松解析并提取周数,下面是完整的实现方案:

完整代码示例

from datetime import datetime

# 你的原始时间戳列表
timestamp_list = [
    "Sep 12 2019 21:28:11 1",
    "Sep 12 2019 21:28:11 2",
    "Oct 13 2019 21:28:11 3",
    "Oct 14 2019 21:28:11 4",
    "Nov 15 2019 21:28:11"
]

# 遍历处理每个时间戳
for idx, timestamp in enumerate(timestamp_list, 1):
    try:
        # 清理字符串:去掉末尾的数字标记(比如" 1"、" 2")
        cleaned_timestamp = timestamp.rsplit(' ', 1)[0] if timestamp.split()[-1].isdigit() else timestamp
        
        # 解析时间戳为datetime对象,匹配格式:月份缩写 日期 年份 时分秒
        dt = datetime.strptime(cleaned_timestamp, "%b %d %Y %H:%M:%S")
        
        # 提取ISO标准周数(周一为一周起始,一年第一周至少含4天)
        iso_week = dt.isocalendar()[1]
        # 或者用另一种方式(%W以周一为起始,%U以周日为起始,注意跨年情况)
        # week_num = dt.strftime("%W")
        
        print(f"时间戳{idx}: {timestamp} 对应的ISO周数: {iso_week}")
    except ValueError as e:
        print(f"处理时间戳{idx}: {timestamp} 时出错: {e}")

代码关键部分解释

  • 字符串清理:你的部分时间戳末尾带了数字标记(比如" 1"),用rsplit(' ', 1)[0]可以快速去掉最后一个空格和后面的数字,保证格式统一。
  • 时间格式匹配:%b对应英文月份缩写(比如"Sep"、"Oct"),%d是两位日期,%Y是四位年份,这个格式完全匹配你的时间戳样式。
  • 周数提取:
    • isocalendar()[1]返回的是ISO标准周数,这是国际通用的周计算方式(周一为一周第一天,每年第一周至少包含4天在当年),推荐使用这个。
    • 如果需要按本地习惯(比如周日为一周起始),可以用strftime("%W")(周一起始)或strftime("%U")(周日起始),但要注意跨年时的周数计算差异。
  • 异常处理:加入try-except可以避免个别格式错误的时间戳导致整个脚本崩溃,容错性更强。

运行结果示例

时间戳1: Sep 12 2019 21:28:11 1 对应的ISO周数: 37
时间戳2: Sep 12 2019 21:28:11 2 对应的ISO周数: 37
时间戳3: Oct 13 2019 21:28:11 3 对应的ISO周数: 41
时间戳4: Oct 14 2019 21:28:11 4 对应的ISO周数: 41
时间戳5: Nov 15 2019 21:28:11 对应的ISO周数: 46

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 15:32:45