Bài viết này mình sẽ hướng dẫn các bạn lấy list các tháng giữa 2 date cho trứơc, hoặc các tháng trong năm trong Python 3:
Lấy danh sách các tháng giữa 2 khoảng thời gian
Đầu tiên mình tạo 1 file Datetime Helper có nội dung như sau:
from datetime import datetime
from dateutil.rrule import rrule, MONTHLY
class DateTimeHelper:
@staticmethod
def list_of_months_between_two_dates(start_date, end_date, input_format="%Y-%m-%d", output_format="%Y-%m"):
"""
List months between two dates
:param start_date:
:param end_date:
:param input_format:
:param output_format:
:return: [%Y1-%m1, %Y2-%m2]
"""
# Convert string to time
start_datetime = datetime.strptime(start_date, input_format)
end_datetime = datetime.strptime(end_date, input_format)
# Return list
return [dt.strftime(output_format) for dt in rrule(MONTHLY, dtstart=start_datetime, until=end_datetime)]
Sau đó mình viết đoạn code để lấy thông tin các tháng giữa 2 khoảng thời gian như sau:
from DateTimeHelper import DateTimeHelper start_date = '2022-01-01' end_date = '2022-12-01' list_of_months = DateTimeHelper.list_of_months_between_two_dates(start_date, end_date) print(list_of_months)
Kết quả chạy thì mình thu được:

Lấy danh sách các tháng trong 1 năm
Trường hợp bạn muốn lấy danh sách các tháng trong 1 năm thì có thể viết đơn giản như sau:
year = '2022' list_months_of_year = ["%s-%02d" % (year, i) for i in range(1, 13)] print(list_months_of_year)
Kết quả:

Nguồn: vinasupport.com