Python日期和时间处理(三) - 周数转换

周数的转换

• 日期转换周数
当我们需要获取特定日期对应的周数的时候，通常我们使用如下方法：
``````from datetime import date
dt1 = date(2018, 10, 10)
dt2 = date(2018, 12, 31)
dt1.strftime("%V")   # output: '41'
dt2.strftime("%V")  # output '1'
``````

``````def get_week_number(dt):
"""get both year and week number of a specified date object

:param dt: date or datetime object which you want to corresponding get week number
:return: a tuple including both year and week number. (year, week_num)
"""
year = dt.year
month = dt.month
week_num = int(dt.strftime("%V"))
if dt.month == 12 and week_num == 1:
return year + 1, week_num
return year, week_num
``````

``````get_week_number(d2)
# output: (2019, 1)
``````
• 通过周数转化为特定日期
周数转化为特定日期时，我们其实不仅需要周数，还需要year和一周的第几天，这样才能知道具体是那一天，即：
• year
• week number
• 一周的第几天

``````dt3 = datetime.strptime("2018-41-3", "%Y-%W-%w")
dt3  # output:  datetime.datetime(2018, 10, 10, 0, 0)

dt4 = datetime.strptime("2019-1-1", "%Y-%W-%w")
dt4  # output:  datetime.datetime(2019, 1, 7, 0, 0)

dt5 = datetime.strptime("2018-41-0", "%Y-%W-%w")
dt5  # output:  datetime.datetime(2018, 10, 14, 0, 0)
``````

``````pip install isoweek
``````

``````from isoweek import Week

dt6 = Week(2019, 1).monday()
dt6  # output: datetime.date(2018, 12, 31)
``````