我无法弄清楚如何用年,日和星期来回月。现在我只是想开发一个可以做到这一点的Python脚本。完成此脚本后的目标是将其用于Spark SQL查询以查找月份,因为在我的数据中,每行给出一天,一年和一周。
截至目前,我的python代码看起来像这样。此代码仅适用于我在print中的语句(getmonth(2,30,2018)返回7.我已经尝试了其他日期,输出只是“无”。我也尝试了变量,但没有成功。< / p>
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)
答案 0 :(得分: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]>
答案 1 :(得分:0)
这是一个蛮力方法,循环一年中的几天(它预计星期一为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)))
用于获取我们尚未使用的所有日期的第一个月,即您当前所在的月份。
答案 2 :(得分: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'
>>>