Python: give start and end of week data from a given date

前端 未结 3 1794
醉梦人生
醉梦人生 2020-11-28 06:19
day = \"13/Oct/2013\"
print(\"Parsing :\",day)
day, mon, yr= day.split(\"/\")
sday = yr+\" \"+day+\" \"+mon
myday = time.strptime(sday, \'%Y %d %b\')
Sstart = yr+\"          


        
相关标签:
3条回答
  • 2020-11-28 06:25

    Use the pendulum module:

    today = pendulum.now()
    start = today.start_of('week')
    end = today.end_of('week')
    
    0 讨论(0)
  • 2020-11-28 06:28

    Use the datetime module.

    This will yield start and end of week (from Monday to Sunday):

    from datetime import datetime, timedelta
    
    day = '12/Oct/2013'
    dt = datetime.strptime(day, '%d/%b/%Y')
    start = dt - timedelta(days=dt.weekday())
    end = start + timedelta(days=6)
    print(start)
    print(end)
    

    EDIT:

    print(start.strftime('%d/%b/%Y'))
    print(end.strftime('%d/%b/%Y'))
    
    0 讨论(0)
  • 2020-11-28 06:43

    Slight variation if you want to keep the standard time formatting and refer to the current day:

    from datetime import datetime, timedelta
    
    today = datetime.now().date()
    start = today - timedelta(days=today.weekday())
    end = start + timedelta(days=6)
    print("Today: " + str(today))
    print("Start: " + str(start))
    print("End: " + str(end))
    
    0 讨论(0)
提交回复
热议问题