更新:帖子已編輯以添加帖子結尾的答案
核心問題
使用 Python,如何輸出某個日期范圍后 6 周的星期二日期?
語境
我在一家 SaaS 公司作業,擔任面向客戶的角色。每當我為客戶進行實施時,客戶都會在星期二收到一封調查電子郵件,這發生在我們初次互動后的第 6 周。
要知道哪個星期二特別好,我們目前必須參考一個圖表,說明如果互動在日期范圍 x 內,那么客戶會在 y 星期二收到他們的調查請求。
例如:如果互動發生在 4 月 18 日至 4 月 22 日之間的某個時間,則調查將于 5 月 31 日結束。
我寧愿這樣做,而不必將日期范圍及其相應的星期二硬編碼到我的程式中(只是因為我很懶,不想隨著月份的推移手動更新日期),但我如果必須這樣,我對那個解決方案持開放態度。:)
代碼嘗試
我可以使用 datetime 從今天的日期輸出 x 周的特定日期,但我不確定如何從這里到達我想要做的事情。
import time
from datetime import datetime, timedelta
time1 = (time.strftime("%m/%d/%Y")) #current date
time2 = ((datetime.now() timedelta(weeks=6)).strftime('%m/%d/%Y')) #current date six weeks
print(time1)
print((datetime.now() timedelta(weeks=6)).strftime('%m/%d/%Y'))
免責宣告: 我是初學者,雖然我在發布之前確實搜索了這個問題的答案,但我可能不知道要使用的正確術語。如果這是一個重復的問題,我會很高興被指出正確的方向。:)
~~~更新的答案~~~
感謝@Mandias 讓我走上正軌。我能夠使用周數來達到我想要的結果。
from datetime import datetime, timedelta, date
today = date.today() #get today's date
todays_week = today.isocalendar()[1] #get the current week number based on today's date
survey_week = todays_week 6 #add 6 weeks to the current week number
todays_year = int(today.strftime("%Y")) #get today's calendar year and turn it from a str to an int
survey_week_tuesday = date.fromisocalendar(todays_year, survey_week, 2) #(year, week, day of week) 2 is for Tuesday
print("Current Week Number:")
print(todays_week)
print("Current Week Number 6 Weeks:")
print(todays_week 6)
print("Today's Year:")
print(todays_year)
print("The Tuesday on the 6th week from the current week (i.e. survey tuesday):")
print(survey_week_tuesday.strftime('%m-%d-%Y')) #using strftime to format the survey date into MM-DD-YYYY format because that's what we use here even though DD-MM-YYYY makes more sense
uj5u.com熱心網友回復:
我相信您正在尋找的內容顯示在下面的示例代碼中:
from datetime import datetime, timedelta
# Establish your date range
start = datetime.strptime("12-17-2010", "%m-%d-%Y")
end = datetime.strptime("1-05-2011", "%m-%d-%Y")
elapsed_days = (end-start).days
# Get each day in that range offset by 6 weeks
# You may need to adjust the elapsed_days value
offset = 6 #weeks
offset_days = [start timedelta(weeks=offset, days=i) for i in range(elapsed_days)]
print(offset_days)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/472609.html
