Python - Calculate the date of last week's 5

巴扎黑
Release: 2016-12-03 10:23:28
Original
1468 people have browsed it

The first method:

from datetime import datetime, timedelta  
weekdays = ['Monday','Tuesday','Wednesday','Thursday',  
            'Friday','Saturday','Sunday']  
def get_previous_byday(dayname, start_date=None):  
    if start_date is None:  
        start_date = datetime.today()  
    day_num = start_date.weekday()  
    day_num_target = weekdays.index(dayname)  
    days_ago = (7 + day_num - day_num_target) % 7  
    if days_ago == 0:  
        days_ago = 7  
    target_date = start_date - timedelta(days = days_ago)  
    return target_date  
  
print( datetime.today() )  
print( get_previous_byday('Monday') )  
print( get_previous_byday('Monday', datetime(2016, 8, 28)) )
Copy after login

The second method, use the dateutil module

from datetime import datetime  
from dateutil.relativedelta import relativedelta  
from dateutil.rrule import *  
d = datetime.now()  
print(d)  
print(d + relativedelta(weekday=FR))  
print(d + relativedelta(weekday=FR(-1)))
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!