【问题标题】:Python date format jan 1,2012 - jan 31,2012Python 日期格式 2012 年 1 月 1 日 - 2012 年 1 月 31 日
【发布时间】:2012-01-06 05:19:31
【问题描述】:

我想以 2012 年 1 月 1 日 - 2012 年 1 月 31 日的格式显示日期 并获取包含日期范围的列表['jan 1,2012 - jan 31,2012','December 1,2011 - December 31,2011','November 1,2011 - November 3o,2011'...'February 1, 2011 - 2011 年 2 月 28 日']

即当前月份之前的所有 12 个月。 有任何想法吗??? 请帮忙!!!!!

【问题讨论】:

    标签: python date


    【解决方案1】:

    这是使用datetimecalendar 模块的解决方案:

    import calendar
    import datetime
    
    current = datetime.date.today().replace(day=1)
    mylist = list()
    for i in xrange(12):
        rng = calendar.monthrange(current.year, current.month)
        last = current.replace(day = rng[1])
        mylist.append(current.strftime("%b 1, %Y") + " - " + last.strftime("%b %d, %Y"))
        current = (current - datetime.timedelta(1)).replace(day=1)
    print mylist
    

    当我运行它时,它会打印:

    ['Jan 1, 2012 - Jan 31, 2012', 'Dec 1, 2011 - Dec 31, 2011', 'Nov 1, 2011 - Nov 30, 2011', 'Oct 1, 2011 - Oct 31, 2011', 'Sep 1, 2011 - Sep 30, 2011', 'Aug 1, 2011 - Aug 31, 2011', 'Jul 1, 2011 - Jul 31, 2011', 'Jun 1, 2011 - Jun 30, 2011', 'May 1, 2011 - May 31, 2011', 'Apr 1, 2011 - Apr 30, 2011', 'Mar 1, 2011 - Mar 31, 2011', 'Feb 1, 2011 - Feb 28, 2011']
    

    【讨论】:

    • 很好,我之前没见过 calendar.monthrange 方法。 +1
    【解决方案2】:

    这有点小技巧,但希望有人能告诉你一个更好的方法:

    由于期间没有那么多天,您可以通过暴力生成所有日期:

    import datetime
    for year in range(2011,2013):
        for month in range(1,13):
            for day in range(28,32):
                try:
                    _date=datetime.date(year,month,day)
                except ValueError:
                    print month,day
    
    output:
    2 29
    2 30
    2 31
    4 31
    6 31
    9 31
    11 31
    2 30
    2 31
    4 31
    6 31
    9 31
    11 31
    

    基本上使用这种蛮力方法,您可以计算出每个月的最大日期。

    我建议: 使用这种技术,创建代表每个月的最大日期的日期对象列表。

    为每个月的第一天创建一个日期对象列表。

    对两个列表进行排序

    压缩两个列表

    对于您从压缩列表中获得的每一对,使用 strftime 方法打印您的日期范围

    例如:

    >>> datetime.date.today().strftime("%a")
    'Fri'
    

    如果您查看页面中间的http://docs.python.org/library/time.html,它会告诉您传递 strftime 的内容以获得您想要的格式。 “%a”就是一个例子

    【讨论】:

    • 这够你过去了吗?还是要我完善我的答案?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 1970-01-01
    • 2021-07-13
    相关资源
    最近更新 更多