如何获取日期之间的周期?

我有两个月的时间,从开始到结束。我想迭代之间的所有月份,即我想将所有月份提取为循环中的字符串。


start = '1905' # May 2019

end = '2003' # March 2020


for month in range(start, end):

     # I want to get string of each month in same format here

有人可以帮助我干净有效地获得这个吗?我的一年总是在(2000-2099)之间


至尊宝的传说
浏览 103回答 4
4回答

慕容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 = {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '01': 'Jan',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '02': 'Feb',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '03': 'Mar',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '04': 'Apr',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '05': 'May',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '06': 'Jun',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '07': 'Jul',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '08': 'Aug',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '09': 'Sep',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '10': 'Oct',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '11': 'Nov',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '12': 'Dec'&nbsp; &nbsp; &nbsp; &nbsp; }start = '1905'end = '2003'for i, j in enumerate(range(int(start[0:2]), int(end[0:2])+1)):&nbsp; if i == 0 and start[0:2] != end[0:2]:&nbsp; &nbsp; s = int(start[2:4])&nbsp; &nbsp; e = 12&nbsp; if i > 0 and start[0:2] != end[0:2] and j != int(end[0:2]):&nbsp; &nbsp; s = 1&nbsp; &nbsp; e = 12&nbsp; if i > 0 and start[0:2] != end[0:2] and j == int(end[0:2]):&nbsp; &nbsp; s = 1&nbsp; &nbsp; e = int(end[2:4]) + 1&nbsp; &nbsp;&nbsp;&nbsp; if i == 0 and start[0:2] == end[0:2]:&nbsp; &nbsp; s = int(start[2:4])&nbsp; &nbsp; e = int(end[2:4]) + 1&nbsp; for p in range(s, e):&nbsp; &nbsp; index = '0' + str(p) if p < 10 else str(p)&nbsp; &nbsp; print(f"Year: {j}, month {months[index]}")&nbsp; &nbsp; 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):&nbsp; &nbsp; # Parse an `YYMM` string into a tuple of (Year, Month)&nbsp; &nbsp; return (2000 + int(yymm_string[:2], 10), int(yymm_string[2:], 10))def ym_pair_to_yymm(ym_pair):&nbsp; &nbsp; # Convert a (Year, Month) tuple into an `YYMM` string&nbsp; &nbsp; return f"{ym_pair[0] - 2000:02d}{ym_pair[1]:02d}"def generate_yms(start, end):&nbsp;&nbsp; &nbsp; parsed_end = parse_yymm_string(end)&nbsp; &nbsp; curr_year, curr_month = parse_yymm_string(start)&nbsp; &nbsp; while (curr_year, curr_month) <= parsed_end:&nbsp; &nbsp; &nbsp; &nbsp; yield (curr_year, curr_month)&nbsp; &nbsp; &nbsp; &nbsp; curr_month += 1&nbsp; &nbsp; &nbsp; &nbsp; if curr_month > 12:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; curr_year += 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; curr_month = 1start = '1905' # May 2019end = '2003' # March 2020for ym in generate_yms('1905', '2003'):&nbsp; &nbsp; 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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python