我知道如何生成日期时间对象
datetime.datetime(2006, 1, 1, 0, 0)
但是如何从2006/1/1到2010/1/1每月生成一系列数据时对象
如
for dt in [datetime.datetime(2006, 1, 1, 0, 0): datetime.datetime(2010, 1, 1, 0, 0)]:
print(dt)
答案 0 :(得分:2)
正如this question所示,在日期时间库中增加月份具有惊人的挑战性。但是,如果您使用dateutil库也会变得更容易:
from dateutil.relativedelta import relativedelta
print [datetime.datetime(2006, 1, 1, 0, 0) + relativedelta(months=i) for i in range(48)]
链接的问题也有一些解决方案可以在没有dateutil的情况下执行此操作,但它们实际上更加麻烦。
答案 1 :(得分:2)
你可以使用简单的循环:
Page Directive
答案 2 :(得分:0)
更新
from calendar import monthrange
import datetime
from dateutil.relativedelta import relativedelta
def monthdelta(d1, d2):
delta = 0
while True:
mdays = monthrange(d1.year, d1.month)[1]
d1 += datetime.timedelta(days=mdays)
if d1 <= d2:
delta += 1
else:
break
return delta
d0 = datetime.datetime(2007, 8, 1,0)
d1 = datetime.datetime(2008, 9, 1,0)
monthdiff = monthdelta(d0,d1)
print [d0 + relativedelta(months=i) for i in range(monthdiff)]
计算 monthDiff 并使用 dateutil
O / P
[datetime.datetime(2007, 8, 1, 0, 0), datetime.datetime(2007, 9, 1, 0, 0), datetime.datetime(2007, 10, 1, 0, 0), datetime.datetime(2007, 11, 1, 0, 0), datetime.datetime(2007, 12, 1, 0, 0), datetime.datetime(2008, 1, 1, 0, 0), datetime.datetime(2008, 2, 1, 0, 0), datetime.datetime(2008, 3, 1, 0, 0), datetime.datetime(2008, 4, 1, 0, 0), datetime.datetime(2008, 5, 1, 0, 0), datetime.datetime(2008, 6, 1, 0, 0), datetime.datetime(2008, 7, 1, 0, 0), datetime.datetime(2008, 8, 1, 0, 0)]
答案 3 :(得分:0)
from datetime import datetime
from dateutil.rrule import rrule, MONTHLY
for dt in rrule(MONTHLY, dtstart=datetime(2006, 1, 1), until=datetime(2010, 1, 1)):
print(dt)
答案 4 :(得分:0)
使用@Backtrack提到的calendar.monthrange
使生成器产生每月日期时间。
(日历和日期时间在标准库中可用)
import datetime
from calendar import monthrange
def months(start_datetime, end_datetime):
current_datetime = start_datetime
while current_datetime <= end_datetime:
yield current_datetime
_, days_in_month = monthrange(current_datetime.year, current_datetime.month)
current_datetime += datetime.timedelta(days=days_in_month)
像这样使用:
start = datetime.datetime(2006, 1, 1)
end = datetime.datetime(2010, 1, 1)
for month_datetime in months(start, end):
print(month_datetime)
会给你结果:
datetime.datetime(2006, 1, 1, 0, 0)
datetime.datetime(2006, 2, 1, 0, 0)
datetime.datetime(2006, 3, 1, 0, 0)
datetime.datetime(2006, 4, 1, 0, 0)
datetime.datetime(2006, 5, 1, 0, 0)
datetime.datetime(2006, 6, 1, 0, 0)
datetime.datetime(2006, 7, 1, 0, 0)
...
datetime.datetime(2010, 1, 1, 0, 0)