【问题标题】:Python get months start and end dates for a given yearPython获取给定年份的月份开始日期和结束日期
【发布时间】:2022-04-23 03:26:51
【问题描述】:

我想编写一个 python 函数来获取给定年份的月份开始日期和结束日期。

示例输入:2021

预期输出:

[(01-Jan-2021,31-Jan-2021), (01-Feb-2021,28-Feb-2021), (01-Mar-2021,31-Mar-2021), etc..)]

【问题讨论】:

  • 在stackoverflow上提问之前请自己尝试一下。
  • 除了闰年之外,它们不总是相同的吗?
  • @VishalSingh 不正确。 2 月可以有 29 天!
  • @VishalSingh 谢谢。其实我已经尝试了几种方法来解决这个问题,只是想找到最佳解决方案。

标签: python datetime timedelta


【解决方案1】:

这里的结束日期比较棘手,因为它可以是28293031

您可以使用calendar 模块中的isleap 功能:

from calendar import isleap
import datetime
year = 2024
months_choices = []
for i in range(1, 13):
    month = datetime.date(2021, i, 1).strftime('%b')

    startDate = f"01-{month}-{year}"

    if month in ["Jan", "Mar", "May", "Jul", "Aug", "Oct", "Dec"]:
        endDate = f"31-{month}-{year}"
    elif month in ["Apr", "Jun", "Sep", "Nov"]:
        endDate = f"30-{month}-{year}"
    else:
        isLeap = isleap(1900)
        if isLeap:
            endDate = f"29-{month}-{year}"
        else:
            endDate = f"28-{month}-{year}"

    months_choices.append((startDate, endDate))

print(months_choices)

输出(leap 年):

[('01-Jan-2024', '31-Jan-2024'), ('01-Feb-2024', '29-Feb-2024'), ('01-Mar-2024', '31-Mar-2024'), ('01-Apr-2024', '30-Apr-2024'), ('01-May-2024', '31-May-2024'), ('01-Jun-2024', '30-Jun-2024'), ('01-Jul-2024', '31-Jul-2024'), ('01-Aug-2024', '31-Aug-2024'), ('01-Sep-2024', '30-Sep-2024'), ('01-Oct-2024', '31-Oct-2024'), ('01-Nov-2024', '30-Nov-2024'), ('01-Dec-2024', '31-Dec-2024')]

【讨论】:

  • 感谢您的解决方案!
【解决方案2】:

您可以使用pandasdate ranges,适当的frequency alias 用于月份的开始和结束。例如:

import pandas as pd

year, nMonths = "2020", 12

monthStart = pd.date_range(year, periods=nMonths, freq='MS').strftime("%d-%b-%Y")
monthEnd = pd.date_range(year, periods=nMonths, freq='M').strftime("%d-%b-%Y")

l = [(s,e) for s,e in zip(monthStart, monthEnd)]

l
[('01-Jan-2020', '31-Jan-2020'),
 ('01-Feb-2020', '29-Feb-2020'),
 ('01-Mar-2020', '31-Mar-2020'),
 ('01-Apr-2020', '30-Apr-2020'),
 ('01-May-2020', '31-May-2020'),
 ('01-Jun-2020', '30-Jun-2020'),
 ('01-Jul-2020', '31-Jul-2020'),
 ('01-Aug-2020', '31-Aug-2020'),
 ('01-Sep-2020', '30-Sep-2020'),
 ('01-Oct-2020', '31-Oct-2020'),
 ('01-Nov-2020', '30-Nov-2020'),
 ('01-Dec-2020', '31-Dec-2020')]

【讨论】:

  • 非常感谢!
【解决方案3】:

您实际上只是在检查一年是否是闰,然后确定二月的长度。这可能是一种简单的方法:

import calendar

def MonthsStartAndEnd(year):
    # create dictionary of normal month lengths
    months = {
        'Jan': '31',
        'Feb': '28',
        'Mar': '31',
        'Apr': '30',
        'May': '31',
        'Jun': '30',
        'Jul': '31',
        'Aug': '31',
        'Sep': '30',
        'Oct': '31',
        'Nov': '30',
        'Dec': '31'
    }

    # check if the year is leap and if so update Feb to 29 days
    if calendar.isleap(year):
        months['Feb'] = '29'

    # return the formatted list of values
    return [f"01-{key}-{year},{value}-{key}-{year}" for key, value in months.items()]

print(MonthsStartAndEnd(2000))
print(MonthsStartAndEnd(2001))

#['01-Jan-2000,31-Jan-2000', '01-Feb-2000,29-Feb-2000', '01-Mar-2000,31-Mar-2000', '01-Apr-2000,31-Apr-2000', '01-May-2000,31-May-2000', '01-Jun-2000,31-Jun-2000', '01-Jul-2000,31-Jul-2000', '01-Aug-2000,31-Aug-2000', '01-Sep-2000,31-Sep-2000', '01-Oct-2000,31-Oct-2000', '01-Nov-2000,31-Nov-2000', '01-Dec-2000,31-Dec-2000']
['01-Jan-2001,31-Jan-2001', '01-Feb-2001,28-Feb-2001', '01-Mar-2001,31-Mar-2001', '01-Apr-2001,31-Apr-2001', '01-May-2001,31-May-2001', '01-Jun-2001,31-Jun-2001', '01-Jul-2001,31-Jul-2001', '01-Aug-2001,31-Aug-2001', '01-Sep-2001,31-Sep-2001', '01-Oct-2001,31-Oct-2001', '01-Nov-2001,31-Nov-2001', '01-Dec-2001,31-Dec-2001']

 

【讨论】:

  • 感谢您的解决方案!
  • 如果这对您来说是正确的解决方案,您能否标记为正确?
【解决方案4】:

如果您使用的是 Pandas,period_range 最适合这个(不需要压缩日期系列!):

import pandas as pd
periods = pd.period_range('1/1/2016', freq='M', periods=12) 
print([(p.start_time.strftime('%d-%b-%Y'), p.end_time.strftime('%d-%b-%Y')) for p in periods])
# outputs: [('01-Jan-2016', '31-Jan-2016'), ('01-Feb-2016', '29-Feb-2016'), ...]

所有 pandas 日期/时间功能都可以在这里找到:https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-02
    相关资源
    最近更新 更多