gpt4 book ai didi

python - 日期不按顺序排列

转载 作者:行者123 更新时间:2023-11-30 22:43:50 25 4
gpt4 key购买 nike

为什么从十二月开始?并且 1 1 在末尾重复。迭代给定年份中所有日期的更 Pythonic 方法是什么(处理闰年)?

import calendar

a = calendar.Calendar(0)
for b in range(1,13):
for x in a.itermonthdates(2016,b):
print x.month, x.day

输出:

12 28
12 29
12 30
12 31
1 1
1 2
1 3
..
..
..

完整输出:

http://pastebin.com/nnP4ADQK

最佳答案

itermonthdates返回完整的周数:

itermonthdates(year, month) Return an iterator for the month month (1–12) in the year year. This iterator will return all days (as datetime.date objects) for the month and all days before the start of the month or after the end of the month that are required to get a complete week.

您可以拒绝年份不是 2016 年的日期:

import calendar

a = calendar.Calendar(0)
g = (x for b in xrange(1, 13) for x in a.itermonthdates(2016, b) if x.year == 2016)
print next(g)

输出:

2016-01-01

关于python - 日期不按顺序排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41657190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com