-
慕容708150
period_range与将日期字符串转换为日期时间一起使用:start = '1905' # May 2019end = '2003' # March 2020p = pd.period_range(pd.to_datetime(start, format="%y%m"), pd.to_datetime(end, format="%y%m"), freq='M')print (p)PeriodIndex(['2019-05', '2019-06', '2019-07', '2019-08', '2019-09', '2019-10', '2019-11', '2019-12', '2020-01', '2020-02', '2020-03'], dtype='period[M]', freq='M')然后用于PeriodIndex.strftime自定义格式:print (p.strftime('%B'))Index(['May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', 'January', 'February', 'March'], dtype='object')for val in p: print (val)
-
回首忆惘然
一个简单的解决方案是这样的:months = { '01': 'Jan', '02': 'Feb', '03': 'Mar', '04': 'Apr', '05': 'May', '06': 'Jun', '07': 'Jul', '08': 'Aug', '09': 'Sep', '10': 'Oct', '11': 'Nov', '12': 'Dec' }start = '1905'end = '2003'for i, j in enumerate(range(int(start[0:2]), int(end[0:2])+1)): if i == 0 and start[0:2] != end[0:2]: s = int(start[2:4]) e = 12 if i > 0 and start[0:2] != end[0:2] and j != int(end[0:2]): s = 1 e = 12 if i > 0 and start[0:2] != end[0:2] and j == int(end[0:2]): s = 1 e = int(end[2:4]) + 1 if i == 0 and start[0:2] == end[0:2]: s = int(start[2:4]) e = int(end[2:4]) + 1 for p in range(s, e): index = '0' + str(p) if p < 10 else str(p) print(f"Year: {j}, month {months[index]}") print(f"{j}{index}")输出:Year: 19, month May1905Year: 19, month Jun1906Year: 19, month Jul1907Year: 19, month Aug1908Year: 19, month Sep1909Year: 19, month Oct1910Year: 19, month Nov1911Year: 20, month Jan2001Year: 20, month Feb2002Year: 20, month Mar2003
-
沧海一幻觉
您可以使用date及其格式:from datetime import date, datetimedef parse(strg): return datetime.strptime(strg, "%y%m").date()start = parse("1905")end = parse("2003")dt = startwhile dt <= end: print(f"{dt:%y%m} - {dt:%B %Y}") dt = date(year=dt.year + dt.month // 12, month=(dt.month % 12) + 1, day=1) 这将产生字符串1905 - May 20191906 - June 20191907 - July 20191908 - August 20191909 - September 20191910 - October 20191911 - November 20191912 - December 20192001 - January 20202002 - February 20202003 - March 2020date使用格式字符串格式化对象"%y%m"将返回您想要的格式。
-
繁星淼淼
像这样的生成器函数应该可以解决问题。def parse_yymm_string(yymm_string): # Parse an `YYMM` string into a tuple of (Year, Month) return (2000 + int(yymm_string[:2], 10), int(yymm_string[2:], 10))def ym_pair_to_yymm(ym_pair): # Convert a (Year, Month) tuple into an `YYMM` string return f"{ym_pair[0] - 2000:02d}{ym_pair[1]:02d}"def generate_yms(start, end): parsed_end = parse_yymm_string(end) curr_year, curr_month = parse_yymm_string(start) while (curr_year, curr_month) <= parsed_end: yield (curr_year, curr_month) curr_month += 1 if curr_month > 12: curr_year += 1 curr_month = 1start = '1905' # May 2019end = '2003' # March 2020for ym in generate_yms('1905', '2003'): print(ym, ym_pair_to_yymm(ym))输出是(2019, 5) 1905(2019, 6) 1906(2019, 7) 1907(2019, 8) 1908(2019, 9) 1909(2019, 10) 1910(2019, 11) 1911(2019, 12) 1912(2020, 1) 2001(2020, 2) 2002(2020, 3) 2003