我将讨论总结为两个步骤:
- 将原始格式转换为
datetime 对象。
- 使用
datetime对象或date对象的函数计算周数。
热身
from datetime import datetime, date, time
d = date(2005, 7, 14)
t = time(12, 30)
dt = datetime.combine(d, t)
print(dt)
第一步
要手动生成datetime对象,我们可以使用datetime.datetime(2017,5,3)或datetime.datetime.now()。
但实际上,我们通常需要解析一个现有的字符串。我们可以使用strptime 函数,例如datetime.strptime('2017-5-3','%Y-%m-%d'),您必须在其中指定格式。不同格式代码的详细信息可以在official documentation中找到。
另外,更方便的方法是使用dateparse 模块。例如dateparser.parse('16 Jun 2010')、dateparser.parse('12/2/12') 或dateparser.parse('2017-5-3')
以上两种方法都会返回一个datetime对象。
第二步
使用获取到的datetime对象调用strptime(format)。例如,
蟒蛇
dt = datetime.strptime('2017-01-1','%Y-%m-%d') # return a datetime object. This day is Sunday
print(dt.strftime("%W")) # '00' Monday as the 1st day of the week. All days in a new year preceding the 1st Monday are considered to be in week 0.
print(dt.strftime("%U")) # '01' Sunday as the 1st day of the week. All days in a new year preceding the 1st Sunday are considered to be in week 0.
print(dt.strftime("%V")) # '52' Monday as the 1st day of the week. Week 01 is the week containing Jan 4.
决定使用哪种格式非常棘手。更好的方法是获取一个date 对象来调用isocalendar()。例如,
蟒蛇
dt = datetime.strptime('2017-01-1','%Y-%m-%d') # return a datetime object
d = dt.date() # convert to a date object. equivalent to d = date(2017,1,1), but date.strptime() don't have the parse function
year, week, weekday = d.isocalendar()
print(year, week, weekday) # (2016,52,7) in the ISO standard
实际上,您更有可能使用date.isocalendar() 来准备每周报告,尤其是在Christmas-New Year 购物旺季。