python - Week number of the month

后端 未结 14 1431
忘掉有多难
忘掉有多难 2020-12-01 08:11

Does python offer a way to easily get the current week of the month (1:4) ?

14条回答
  •  一向
    一向 (楼主)
    2020-12-01 08:53

    This version could be improved but as a first look in python modules (datetime and calendar), I make this solution, I hope could be useful:

    from datetime import datetime
    n = datetime.now()
    #from django.utils.timezone import now
    #n = now() #if you use django with timezone
    
    from calendar import Calendar
    cal = Calendar() # week starts Monday
    #cal = Calendar(6) # week stars Sunday
    
    weeks = cal.monthdayscalendar(n.year, n.month)
    for x in range(len(weeks)):
        if n.day in weeks[x]:
            print x+1
    

提交回复
热议问题