Home > database >  How to get week number between two months?
How to get week number between two months?

Time:11-13

I am running sql query in python, I have a requirement to dynamically generate dates and append it to my sql query.This script runs on every Monday. If the week of Monday falls between two months then I have to restrict the date range till last of the previous month (i.e 30th or 31st). Any Ideas on how to achieve this ?

I tried to get the weeknumber and their respective dates but I couldn't find the exact function which will return me list of dates with corresponding week number

CodePudding user response:

You can use the following code to get the week number between two months:

import datetime

def get_weeks_between_dates(start_date, end_date):
    start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
    end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
    week_number = (end_date - start_date).days / 7
    return week_number

start_date = '2017-01-01'
end_date = '2017-02-01'
print(get_weeks_between_dates(start_date, end_date))

CodePudding user response:

Find the possibly truncated week starting at a given date and not extending beyond the end of the month.

If what you mean is "the seven days starting with the day the script is run", you could use the following:

from datetime import date, timedelta, datetime as dt
from typing import Tuple

def one_week_from(base: None | date = None) -> Tuple[date, date]:
    '''Returns a tuple consisting of the given starting date (default today)
       and the end of the week starting at that date, or the last day of the
       month, whichever comes first. (That is, a week truncated at the end of
       the month.)
    '''
    if base is None:
        base = dt.now().date()
    if base.month < 12:
        next_first = date(base.year, base.month   1, 1)
    else:
        next_first = date(base.year   1, 1, 1))
    return (base, min(base   timedelta(6), next_first - timedelta(1)))

If necessary, you could use a function like this to find a Monday:

# Same imports as above
def monday_not_later_than(base: None | date = None) -> date:
    '''Returns the last Monday no later than the given date (default: today).
       (That is, the given date if it is a Monday; otherwise the previous
       Monday.)
    '''
    if base is None:
        base = dt.now().date()
    return base - timedelta(base.weekday())

Get the ISO week number

If you have a datetime.date or datetime.datetime object, you can use the isocalendar() member function to get a tuple consisting of the year, week_number and iso_day_of_week for that date. (Use datetime.datetime.now() to get the current day, but watch out for time zone artefacts.)

The ISO week always starts with a Monday; it is counted in the year which contains the Wednesday of the week. The ISO weekday is from 1 to 7 (Monday == 1), unlike the datetime.date.weekday which ranges from 0 to 6 (Monday == 0).

  • Related