2017-06-16 80 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)))用于获取的是,第一个月我们都没有使用所有的日子,也就是本月你在目前是