Feb 5, 2019

Python week of the month

from math import ceil
from datetime import datetime

def week_of_month(dt):
#This will add the first day of the month weekday & present day of month
    first_day = dt.replace(day=1)
    day_of_month = dt.day
    #print day_of_month
    adj_day_of_month = day_of_month + first_day.weekday()
    return int(ceil(adj_day_of_month/7.0))

if __name__ == '__main__':
    #dt = datetime.now()
    #dt = datetime.strptime('Feb 21 2019  1:00PM', '%b %d %Y %I:%M%p')
    dt = datetime.strptime('Feb 19 2019', '%b %d %Y')
    print dt
    print week_of_month(dt)

"""
Output:
2019-02-19 00:00:00
3
"""

No comments:

Post a Comment