2016-07-07 84 views
-2

需要確定上個星期四的任何給定月份。如果給定的月份是當前月份,並且上個星期四已過,則需要提出例外。我正在嘗試使用datetime模塊,但無法找到這樣做的簡單方法。需要獲取python中給定月份的上個星期四的日期嗎?

編輯:好像我的問題不夠清楚。我查找的函數將返回給定月份的最後一個星期四的日期,以便該月份的返回日期之後的任何日期均不應爲星期四。這個問題似乎已經被CrackaJackDev和af3ld有效地解決了。謝謝你。也非常感謝Bahrom進行關鍵編輯和修正。我對這個社區很陌生,如果我的問題組織得不好,我很抱歉。下次我會更努力。

+0

我有不知道你在說什麼。你能詳細解釋一下你的問題嗎? – refi64

回答

1

下面是一個不依賴於任何外部包版本:

import datetime, calendar 

def LastThInMonth(year, month): 
    # Create a datetime.date for the last day of the given month 
    daysInMonth = calendar.monthrange(year, month)[1] # Returns (month, numberOfDaysInMonth) 
    dt = datetime.date(year, month, daysInMonth) 

    # Back up to the most recent Thursday 
    offset = 4 - dt.isoweekday() 
    if offset > 0: offset -= 7       # Back up one week if necessary 
    dt += datetime.timedelta(offset)     # dt is now date of last Th in month 

    # Throw an exception if dt is in the current month and occurred before today 
    now = datetime.date.today()       # Get current date (local time, not utc) 
    if dt.year == now.year and dt.month == now.month and dt < now: 
     raise Exception('Oops - missed the last Thursday of this month') 

    return dt 

for month in range(1, 13): print(LastThInMonth(2016, month)) 

2016-01-28 
2016-02-25 
2016-03-31 
2016-04-28 
2016-05-26 
2016-06-30 
2016-07-28 
2016-08-25 
2016-09-29 
2016-10-27 
2016-11-24 
2016-12-29 
1

對於您的問題的第一部分,我喜歡date.utils庫中的relativedelta

from datetime import date 
from dateutil.relativedelta import relativedelta, TH 

def get_thurs(dt): 
    print (dt + relativedelta(day=31, weekday=TH(-1))) 

get_thurs(date(2016, 7, 7)) 
get_thurs(date(2019, 6, 4)) 


2016-07-28 
2019-06-27 

對於第二部分,我想你想的東西有點像這樣:

def get_thurs(dt): 
    return (dt + relativedelta(day=31, weekday=TH(-1))) 


def later_date(dt): 
    if dt.month == date.today().month: # checks if in current month 
     if get_thurs(dt).day > dt.day: # checks if last Thurs has passed 
      raise Exception 
     else: 
      print "It is before that Thursday" 


later_date(date(2016, 7, 23)) 
later_date(date(2016, 7, 29)) 


It is before that Thursday 
Traceback (most recent call last): 
    File "calculator/bw_events_cookies/tests/ideas.py", line 31, in <module> 
    later_date(date(2016, 7, 23)) 
    File "calculator/bw_events_cookies/tests/ideas.py", line 26, in later_date 
    raise Exception 
Exception 
相關問題