2017-06-16 81 views
0

我無法弄清楚如何利用年份,日期和星期來返回月份。現在我只是想開發一個能夠做到這一點的Python腳本。完成此腳本後的目標是將其用於Spark SQL查詢來查找月份,因爲在我的數據中,每一行都有一天,一年和一週。從日,周和年的查找月份Python

截至目前我的Python代碼看起來像這樣。這段代碼只適用於我在print中使用的語句(getmonth(2,30,2018))返回7.我嘗試過其他日期,輸出只有「None」。我也嘗試過變量,但沒有成功。

import datetime 

def month(day, week, year): 
    for month in range(1,13): 
     try: 
      date = datetime.datetime(year, month, day) 
     except ValueError: 
      iso_year, iso_weeknum, iso_weekday = date.isocalendar() 
      if iso_weeknum == week: 
       return date.month 
print(getmonth(2, 30, 2018)) 


#iso_(year,weeknum,weekday) are the classes for ISO. Year is 1-9999, weeknum is 0-52 or 53, and weekday is 0-6 
#isocaldenar is a tuple (year, week#, weekday) 
+1

它不應該是'def getmonth(day,week,year):'或'print(month(28,30,2018))'? 您的代碼也會在'print(month(28,30,2018))'返回'None'。 – Deuce

+0

'if'只有在發生異常時纔會到達,您應該將它移動到'try'塊或通過一個級別的unindent塊 – mugiseyebrows

+0

@Deuce def getmonth(day,week,year)也返回none – Travis

回答

0

我真的不明白你的問題,但我認爲日期時間將工作... sorce: Get date from ISO week number in Python

>>> from datetime import datetime 
>>> day = 28 
>>> week = 30 
>>> year = 2018 
>>> t = datetime.strptime('{}_{}_{}{}'.format(day,week,year,-0), '%d_%W_%Y%w') 
>>> t.strftime('%W') 
'30' 
>>> t.strftime('%m') 
'07' 
>>> 
0

一個簡單的辦法可以使用pendulum庫中創建作爲你的代碼,遍歷月號,創建日期,比較周爲這些日期對所需的日期。如果發現停止循環;如果日期沒有見過然後退出有,比方說,一個-1循環。

>>> import pendulum 
>>> for month in range(1,13): 
...  date = pendulum.create(2018, month, 28) 
...  if date.week_of_year == 30: 
...   break 
... else: 
...  month = -1 
...  
>>> month 
7 
>>> date 
<Pendulum [2018-07-28T00:00:00+00:00]> 
0

這裏是通過一年的天環強力方法(該公司預計當日爲週一爲0和週日爲6,它也返回0個月索引,1月份是0,十二月份爲11):

import datetime 

def month(day, week, year): 
    #Generate list of No of days of the month 
    months = [31,28,31,30,31,30,31,31,30,31,30,31] 
    if((year % 4 == 0 and year % 100 != 0) or year % 400 == 0): months[1] += 1 

    #ISO wk1 of the yr is the first wk with a thursday, otherwise it's wk53 of the previous yr 
    currentWeek = 1 if day < 4 else 0 

    #The day that the chosen year started on 
    currentDay = datetime.datetime(year, 1, 1).weekday() 

    #Loop over every day of the year 
    for i in range(sum(months)): 
     #If the week is correct and day is correct you're done 
     if day == currentDay and week == currentWeek: 
      return months.index(next(filter(lambda x: x!=0, months))) 

     #Otherwise, go to next day of wk/next wk of yr 
     currentDay = (currentDay + 1) % 7 
     if currentDay == 0: 
      currentWeek += 1 

     #And decrement counter for current month 
     months[months.index(next(filter(lambda x: x!=0, months)))]-=1 

print(month(2, 30, 2018)) # 6 i.e. July 

months.index(next(filter(lambda x: x!=0, months)))用於獲取的是,第一個月我們都沒有使用所有的日子,也就是本月你在目前是