I summarize the discussion to two steps:
datetime
object.datetime
object or a date
object to calculate the week number.Warm up
from datetime import datetime, date, time
d = date(2005, 7, 14)
t = time(12, 30)
dt = datetime.combine(d, t)
print(dt)
1st step
To manually generate a datetime
object, we can use datetime.datetime(2017,5,3)
or datetime.datetime.now()
.
But in reality, we usually need to parse an existing string. we can use strptime
function, such as datetime.strptime('2017-5-3','%Y-%m-%d')
in which you have to specific the format. Detail of different format code can be found in the official documentation.
Alternatively, a more convenient way is to use dateparse module. Examples are dateparser.parse('16 Jun 2010')
, dateparser.parse('12/2/12')
or dateparser.parse('2017-5-3')
The above two approaches will return a datetime
object.
2nd step
Use the obtained datetime
object to call strptime(format)
. For example,
python
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.
It's very tricky to decide which format to use. A better way is to get a date
object to call isocalendar()
. For example,
python
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
In reality, you will be more likely to use date.isocalendar()
to prepare a weekly report, especially in the Christmas-New Year
shopping season.