我正在嘗試輸出日歷上的日期,例如:2021-02-02 2021-02-03 2021-02-04 2021-02-05 等。我從https://www.tutorialbrain.com復制了此代碼/python-calendar/所以我不明白為什么會出現錯誤。
import calendar
year = 2021
month = 2
cal_obj = calendar.Calendar(firstweekday=1)
dates = cal_obj.itermonthdays(year, month)
for i in dates:
i = str(i)
if i[6] == "2":
print(i, end="")
錯誤:
if i[6] == "2":
IndexError: string index out of range
Process finished with exit code 1
uj5u.com熱心網友回復:
您的代碼和他們的代碼之間存在差異。這是非常微妙的,但它就在那里:
你的:
dates = cal_obj.itermonthdays(year, month)
^^^^ days
他們的:
dates = cal_obj.itermonthdates(year, month)
^^^^^ dates
itermonthdays將月份中的天數回傳為ints,而itermonthdates回傳datetime.dates。
uj5u.com熱心網友回復:
如果您的目標是創建日歷日期串列,您也可以使用以下內容:
import pandas as pd
from datetime import datetime
datelist = list(pd.date_range(start="2021/01/01", end="2021/12/31").strftime("%Y-%m-%d"))
datelist
您可以選擇任何開始日期或結束日期(如果該日期存在)
Output :
['2021-01-01',
'2021-01-02',
'2021-01-03',
'2021-01-04',
'2021-01-05',
'2021-01-06',
'2021-01-07',
'2021-01-08',
'2021-01-09',
'2021-01-10',
'2021-01-11',
'2021-01-12',
...
'2021-12-28',
'2021-12-29',
'2021-12-30',
'2021-12-31']
uj5u.com熱心網友回復:
似乎您是 Python 新手,這i[6]意味著對串列或類串列資料型別的元素進行索引。可以通過以下方式使用 datetime 庫來實作相同的東西
import datetime
start_date = datetime.date(2021, 2, 1) # set the start date in from of (year, month, day)
no_of_days = 30 # no of days you wanna print
day_jump = datetime.timedelta(days=1) # No of days to jump with each iteration, defaut 1
end_date = start_date no_of_days * day_jump # Seting up the end date
for i in range((end_date - start_date).days):
print(start_date i * day_jump)
輸出
2021-02-01
2021-02-02
2021-02-03
2021-02-04
2021-02-05
2021-02-06
2021-02-07
2021-02-08
2021-02-09
2021-02-10
2021-02-11
2021-02-12
2021-02-13
2021-02-14
2021-02-15
2021-02-16
2021-02-17
2021-02-18
2021-02-19
2021-02-20
2021-02-21
2021-02-22
2021-02-23
2021-02-24
2021-02-25
2021-02-26
2021-02-27
2021-02-28
2021-03-01
2021-03-02
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/338420.html
