如何编写函数处理多格式日期区间,计算任务所需年/月数?
问题解决:多格式日期区间转换为月数
问题背景
现有如下DataFrame数据,Task_1列包含多种格式的任务起止日期区间,需要计算每个任务的耗时月数:
import pandas as pd df_1 = pd.DataFrame({ 'Name': ['Robert', 'billy', 'stuart'], 'Task_1': ["'Nov 2022 - Dec 2022'", "'06/2021 - 06/2022'", "'NOV 2022 - 2022'"] })
预期输出:
| Name | Task_1 | Time Required |
|---|---|---|
| Robert | 'Nov 2022 - Dec 2022' | 1 months |
| billy | '06/2021 - 06/2022' | 12 months |
| stuart | 'NOV 2022 - 2022' | 12 months |
原函数未达预期的核心问题:
- 硬编码日期格式
'%B %Y to %B %Y',无法匹配数据中的月/年、月年 - 年等格式,直接触发解析错误。 - 用
timedelta(days=365)计算时长,忽略了闰年、不同月份天数差异,结果不准确,且无法直接得到月数。
解决方案
步骤1:编写通用日期处理函数
实现自动识别多格式日期,对仅含年份的日期默认补全为当年1月1日,再精准计算月份差:
def calculate_months(date_str): # 去除字符串首尾单引号,拆分起止日期 date_str = date_str.strip("'") start_str, end_str = [s.strip() for s in date_str.split('-')] # 通用日期解析:自动识别格式,补全年份型日期的月日 def parse_single_date(s): try: return pd.to_datetime(s, infer_datetime_format=True) except ValueError: # 处理仅年份的情况,如"2022"转为2022-01-01 return pd.to_datetime(f'01/01/{s}') start_date = parse_single_date(start_str) end_date = parse_single_date(end_str) # 计算精确月份差:年差*12 + 月差 months_diff = (end_date.year - start_date.year) * 12 + (end_date.month - start_date.month) return f"{months_diff} months"
步骤2:应用函数到DataFrame
df_1['Time Required'] = df_1['Task_1'].apply(calculate_months) # 查看结果 print(df_1)
运行结果
Name Task_1 Time Required 0 Robert 'Nov 2022 - Dec 2022' 1 months 1 billy '06/2021 - 06/2022' 12 months 2 stuart 'NOV 2022 - 2022' 12 months
内容的提问来源于stack exchange,提问作者Romi
相关产品推荐
相关产品推荐

