python - 逐周、逐日和逐年获取

标签 python python-3.x

我想知道您如何通过给定日期、周数和年份获得月份。

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

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, week, 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, 52, 2014))
# 12

print(getmonth(13, 42, 2014))
# 10

print(getmonth(6, 2, 2015))
# 1

关于python - 逐周、逐日和逐年获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27675323/

相关文章:

python - 当我将带有 self 引用的列表分配给带有切片语法 `mylist[:] = [mylist, mylist, ...]` 的列表副本时,会发生什么?

python - 如何在客户端模式下设置 `spark.driver.memory` - pyspark(版本2.3.1)

python - 如何在 Python 3 中进行随机数迭代?

javascript - 如何在 Python Selenium 中输入自动填充的文本字段

python - 具有不同大小参数的 PuLP 线性规划

python - 使用 Python 下载 URL 的 html - 但启用了 javascript

python - 我应该在 Python 3 中使用编码声明吗?

Python - 将 CSV 文件作为表格打印到控制台

jquery - 如何在 Django 中创建多选框?

python - 如何避免函数名称中的参数类型?