首页 Python python – 按周,日和年逐月获取

python – 按周,日和年逐月获取

我想知道你如何通过给予日,周数和年份来获得月份. 例如,如果你有这样的东西 def getmonth(day, week, year): # by day, week and year calculate the month print (month)getmonth(28, 52, 2014)# print 12getmonth(13, 42, 2014)# prin

我想知道你如何通过给予日,周数和年份来获得月份.

例如,如果你有这样的东西

def getmonth(day,week,year):
    # by day,week and year calculate the month
    print (month)

getmonth(28,52,2014)
# print 12

getmonth(13,42,2014)
# print 10

getmonth(6,2,2015)
# print 1

解决方法


interjay’s suggestion:

import datetime as DT

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

print(getmonth(28,2014))
# 12

print(getmonth(13,2014))
# 10

print(getmonth(6,2015))
# 1

本文来自网络,不代表青岛站长网立场。转载请注明出处: https://www.0532zz.com/html/kaifa/python/20201113/11687.html
上一篇
下一篇

作者: dawei

【声明】:青岛站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

为您推荐

返回顶部