Home  >  Article  >  Backend Development  >  Python实现获取某天是某个月中的第几周

Python实现获取某天是某个月中的第几周

WBOY
WBOYOriginal
2016-06-10 15:17:551438browse

找了半天竟然没找到,如何在Python的datetime处理上,获取某年某月某日,是属于这个月的第几周。

无奈之下求助同学,同学给写了一个模块。【如果你知道Python有这个原生的库,请不吝赐教】

我稍作整理记录在下。

复制代码 代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = '####'
 
import datetime
 
 
def get_week_of_month(year, month, day):
    """
    获取指定的某天是某个月中的第几周
    周一作为一周的开始
    """
    end = int(datetime.datetime(year, month, day).strftime("%W"))
    begin = int(datetime.datetime(year, month, 1).strftime("%W"))
    return end - begin + 1
 
if __name__ == '__main__':
    print get_week_of_month(2015, 1, 4)
    print get_week_of_month(2015, 1, 5)
    print get_week_of_month(2015, 1, 15)
    print get_week_of_month(2015, 1, 18)
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn