我对编码很新,请原谅任何基本错误。我一直在研究这段使用Python日历模块生成开始日期的代码。一切都很顺利,直到我意识到我还需要一个结束日期。我尝试手动将1添加到开始日期,并且我意识到当我打印输出时,一旦它到达月底就不会起作用。 这是我得到的错误输出。显然,12月没有32天。 开课日期是2015-12-31。 截止日期为2015-12-32。 我一直在阅读日历模块上的文档,但我还没有看到任何关于如何使其正常工作的内容(这对我来说很有意义)。 这就是我到目前为止所做的:
import requests
import json
import calendar
cal = calendar.Calendar()
for year in range(2015,2016):
for month in range(1,13):
monthdays = [d for d in cal.itermonthdays(year,month) if d != 0]
for day in monthdays:
str_year = str(year)
if month < 10:
str_month = "0" + str(month)
# print(str_month)
else:
str_month = str(month)
# print(str_month)
if day < 10:
str_StartDay = "0" + str(day)
int_EndDay = day + 1
if int_EndDay < 10:
str_EndDay = "0" + str(int_EndDay)
else:
str_EndDay = str(int_EndDay)
else:
str_StartDay = str(day)
int_EndDay = day + 1
str_EndDay = str(int_EndDay)
# print(str_day)
_STARTDATE = str_year + "-" + str_month + "-" + str_StartDay
_ENDDATE = str_year + "-" + str_month + "-" + str_EndDay
# print(_DATE)
#fun_Phase1(_DATE)
print("Start date is " + _STARTDATE)
print("End date is " + _ENDDATE)
提前致谢。
答案 0 :(得分:0)
谢谢克劳斯D.你指出了我正确的方向。我最终使用datetime来解决这个问题。这是代码。希望这能节省一些时间。
import requests
import json
import calendar
import datetime
cal = calendar.Calendar()
for year in range(2015,2016):
for month in range(1,13):
monthdays = [d for d in cal.itermonthdays(year,month) if d != 0]
for day in monthdays:
str_year = str(year)
int_year = int(year)
if month < 10:
str_month = "0" + str(month)
int_month = int(month)
# print(str_month)
else:
str_month = str(month)
int_month = int(month)
# print(str_month)
if day < 10:
str_StartDay = "0" + str(day)
int_day = int(day)
else:
str_StartDay = str(day)
int_day = int(day)
# print(str_day)
_MYDATE = datetime.date(int_year,int_month,int_day)
str_MYDATE = str(_MYDATE)
print(str_MYDATE)
_MYDATEPLUSONE = _MYDATE + datetime.timedelta(days=1)
str_MYDATEPLUSONE = str(_MYDATEPLUSONE)
print(str_MYDATEPLUSONE)
print("Start date is " + str_MYDATE)
print("End date is " + str_MYDATEPLUSONE)