查找兩個日期之間月份的最佳方法

| | |

我需要能夠在 python 中準確地找到兩個日期之間的月份。我有一個可行的解決方案,但它不是很好(如優雅)或快速。

dateRange = [datetime.strptime(dateRanges[0], "%Y-%m-%d"), datetime.strptime(dateRanges[1], "%Y-%m- %d")] 月 = [] tmpTime = dateRange[0] oneWeek = timedelta(weeks=1) tmpTime = tmpTime.replace(day=1) dateRange[0] = tmpTime dateRange[1] = dateRange[1].replace (day=1) lastMonth = tmpTime.monthmonths.append(tmpTime) 而 tmpTime < dateRange[1]: if lastMonth != 12: while tmpTime.month <= lastMonth: tmpTime += oneWeek tmpTime = tmpTime.replace(day=1) months.append(tmpTime) lastMonth = tmpTime.month else: while tmpTime. month >= lastMonth: tmpTime += oneWeek tmpTime = tmpTime.replace(day=1)months.append(tmpTime) lastMonth = tmpTime.month 

所以只是解釋一下,我是什麼”我在這裡做的是獲取兩個日期並將它們從iso格式轉換為python datetime對象。然後我循環將一周添加到開始日期時間對象並檢查月份的數值是否更大(除非月份是12月那麼它檢查日期是否更小),如果值更大,我將其附加到月份列表中並繼續循環直到我到達結束日期。

它工作得很好,只是看起來不像一個很好的方法......

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method