【问题标题】:Finding Month from Day, Week and Year Python从日、周和年 Python 中查找月份
【发布时间】:2017-11-19 09:58:45
【问题描述】:

我不知道如何用年、日和周来返回月份。现在我只是想开发一个可以做到这一点的 Python 脚本。完成此脚本后的目标是将其用于 Spark SQL 查询以查找月份,因为在我的数据中,我在每一行中都有一天、一年和一周。

到目前为止,我的 python 代码看起来像这样。此代码仅适用于我在 print(getmonth(2, 30 ,2018) 中返回 7 的语句。我尝试了其他日期,输出仅为“无”。我也尝试了变量,但没有成功。

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)

【问题讨论】:

  • 不应该是def getmonth(day, week, year):还是print(month(28, 30, 2018))?您的代码也会为 print(month(28, 30, 2018)) 返回 None
  • if 仅在发生异常时才到达,您应该将其移至 try 块或将其取消缩进一级
  • @Deuce def getmonth(day,week, year) 也没有返回值
  • @Deuce 我明白了。它也应该被移动。 except 块中应该只有 passprint("error") 以满足语法规则。
  • 我不明白输入,第 28 天和第 30 周怎么样?,一周是有意义的,因为它是一年中的第 30 周,但 28 却让我望而却步

标签: python mysql


【解决方案1】:

可以使用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]>

【讨论】:

    【解决方案2】:

    这是一个循环遍历一年中的日子的蛮力方法(它期望星期一为 0,星期日为 6,它还返回索引的第 0 个月,1 月为 0,12 月为 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))) 用于获取我们尚未使用所有天数的第一个月,即您当前所在的月份。

    【讨论】:

      【解决方案3】:

      我不太明白你的问题,但我认为 datetime 会起作用...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'
      >>>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-21
        • 2020-06-08
        相关资源
        最近更新 更多