-4

Any one could help me please, How to get number of week by month in Python?

from datetime import datetime, date, timedelta

Input:

date1 = "2015-07-09"
date2 = "2016-08-20"

Output:

2015-07 : 4
2015-08 : 5
2015-08 : 4
....
2016-08 : 5

How to count number of the week by monthly from date1 to date2?

Mr Theavuth
  • 106
  • 1
  • 3
  • 11

2 Answers2

1

If you wanted to measure the number of full weeks between two dates, you could accomplish this with datetime.strptime and timedelta like so:

from datetime import datetime, date, timedelta
dateformat = "%Y-%m-%d"
date1 = datetime.strptime("2015-07-09", dateformat)
date2 = datetime.strptime("2016-08-20", dateformat)
weeks = int((date2-date1).days/7)
print weeks

This outputs 58. The divide by 7 causes the number of weeks to be returned. The number of whole weeks is used (rather than partial) because of int which returns only the integer portion. If you wanted to get the number of partial weeks, you could divide by 7.0 instead of 7, and ensure that you remove the int piece.

grovesNL
  • 6,016
  • 2
  • 20
  • 32
0

Try this:

date1 = "2015-07-09"
date2 = "2016-08-20"
d1 = datetime.datetime.strptime(date1, '%Y-%m-%d').date()
d2 = datetime.datetime.strptime(date2, '%Y-%m-%d').date()  
diff = d2 -d1
weeks, days = divmod(diff.days, 7)
GAVD
  • 1,977
  • 3
  • 22
  • 40