我被要求創建一個程式來計算兩個日期之間的星期天數!我一直在搜索大量文章和檔案,但我仍然很難理解語法。(進入我的編碼課程 2 個月,技術和計算機經驗為 0。)
我無法理解如何將日歷與字典中的日期相關聯的邏輯。我當前的代碼如下:
def difference_between_days():
daysDict = {0 : "Monday",1: "Tuesday",2: "Wedensday",3: "Thursday",4: "Friday",5:
"Saturday",6: "Sunday"}
first_date = date(2021,7,28)
end_date = date(2022,7,28)
difference_between_dates = end_date - first_date
print(f"There are {difference_between_dates.days} days inbetween the two dates!")
d = date.weekday(first_date)
dd = daysDict[d]
print(f"The first date selected is a : {dd}")
difference_between_days()
編輯:使用某些功能(例如 .isoweekday)時,我遇到了列印問題,因為它回傳了類似“<datetime.date 物件在 0x000001EB956FA0F0> 的內置方法 isoweekday”之類的東西,但我還沒有上課!
uj5u.com熱心網友回復:
Python 不是我選擇的武器,但這應該可以勝任。這個想法是使用 weekday() 將開始日期移至下一個星期日,并將結束日期移至前一個星期日。然后計算中間的天數,除以 7(周)并加 1,因為兩端都是星期日。
如果不清楚,請毫不猶豫地問,如果是,請接受答案。
高溫高壓
from datetime import datetime, timedelta
def number_of_sundays(from_str, to_str):
# get date objects from the string representations in Ymd format
from_date = datetime.strptime(from_str, "%Y/%m/%d")
to_date = datetime.strptime(to_str, "%Y/%m/%d")
# move start date to the following sunday
from_date = from_date timedelta(days=6-from_date.weekday())
# move end date to the previous sunday
to_date = to_date timedelta(days=-to_date.weekday()-1)
# now both dates are sundays so the number is the number of weeks 1
nb_sundays = 1 (to_date - from_date).days / 7
return nb_sundays
print(number_of_sundays("2022/08/28", "2022/09/20"))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/510340.html
下一篇:在同一日期檢索具有給定條件的個人
