0

I want to get week number like picture below

enter image description here

If I insert 20150502, It should print "week 1".

If I insert 20150504, It should print "week 2".

If I insert 20150522, It should print "week 4".

How to get week number?

somputer
  • 235
  • 2
  • 8

1 Answers1

1

Here's a quick attempt, as with all date/time code there are probably a lot of edge cases that can cause strange results.

# dateutil's parser is very good for converting from string to date
from dateutil.parser import parse

date_strs = ['20150502', '20150504', '20150522']

for date_str in date_strs:
    d = parse(date_str)
    month_start = datetime.datetime(d.year, d.month, 1)
    week = d.isocalendar()[1] - month_start.isocalendar()[1] + 1
    print(date_str + ':', week)

Output:

20150502: 1
20150504: 2
20150522: 4
Marius
  • 58,213
  • 16
  • 107
  • 105