【问题标题】:Get the number of week days with date between two dates in python获取python中两个日期之间日期的星期数
【发布时间】:2019-08-02 12:22:21
【问题描述】:

因为我在网站上搜索了 python 中的工作日数,但我也需要工作日的日期。

我的输入将是:

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

预期输出

我需要打印星期一和星期二的数量以及日期。

【问题讨论】:

  • 你能展示一下你尝试过的东西吗

标签: python date python-datetime


【解决方案1】:

试试这个:

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】:

    使用pandas.to_datetimepandas.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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-29
        • 1970-01-01
        • 2017-07-26
        • 1970-01-01
        • 2017-05-02
        相关资源
        最近更新 更多