Get the number of week days with date between two dates in python

萝らか妹 提交于 2021-01-05 12:44:31

问题


As I have searched in website to get the number of weekdays in python, but I need the date of the weekdays too.

My input will be:

 start date = 01-03-2019
 end_date = 15-03-2019
 days = monday , tuesday

Expected Output:

which I need is to print the number of mondays and tuesdays along with the date.


回答1:


Try this :

start_date = '01-03-2019'   # Considering 03 is the month, 01 is the day
end_date = '15-03-2019'    # Considering 03 is the month, 15 is the day
start_date = [int(i) for i in start_date.split("-")]
end_date = [int(i) for i in end_date.split("-")]
days = 'monday' , 'tuesday'
from datetime import timedelta, date
start_date = date(start_date[-1], start_date[1], start_date[0])
end_date = date(end_date[-1], end_date[1], end_date[0])
# Now check in the range of start_date and end_date with condition .weekday() Monday is 0 and Tuesday is 1.
def daterange(start_date, end_date):
    for n in range(int ((end_date - start_date).days)):
        yield start_date + timedelta(n)
for single_date in daterange(start_date, end_date):
    if single_date.weekday() ==0:
        print("Monday : ", single_date)
    if single_date.weekday() == 1:
        print("Tuesday : ", single_date)



回答2:


Use pandas.to_datetime and pandas.date_range:

import pandas as pd

start_date = '01-03-2019'
end_date = '15-03-2019'
days = ['Monday', 'Tuesday']

dates = pd.to_datetime([start_date, end_date], format='%d-%m-%Y')
pd.date_range(dates[0],dates[1],freq='1d').day_name().value_counts()[days]
Monday     2
Tuesday    2
dtype: int64



回答3:


start_date = datetime.strptime(start_date, '%Y-%m-%d')
end_date = datetime.strptime(send_date, '%Y-%m-%d')

step = timedelta(days=1)
while start_date <= end_date:
    for day in days:
        if day == calendar.day_name[start_date.date().weekday()]:
            print calendar.day_name[start_date.date()]
        start_date += step


来源:https://stackoverflow.com/questions/55114536/get-the-number-of-week-days-with-date-between-two-dates-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!