Python - 迭代月份日期并打印自定义输出

标签 python python-3.x

我目前不确定用于以下问题的逻辑,并且也是编程新手。(目前正在学习 python)

尝试遍历给定月份的每个日期 - 例如 05/01 - 05/31 并以以下格式打印出来。

enter image description here

周一至周五的日期将单独打印。 周六和周日日期将单独打印。

如果该月从周五 - 05/01/2020 开始,输出应该是这样的 enter image description here 因为,这是该周的最后一个工作日。

对于 2020 年 4 月,产出如下所示,因为 4 月的第一周从周三开始。

enter image description here

我设法进行了以下尝试,但不确定如何进一步进行。

import sys
from datetime import date, datetime, timedelta

year = int(sys.argv[1])
month = int(sys.argv[2])
st_dt = int(sys.argv[3])
en_dt = int(sys.argv[4])

first_date = datetime(year, month, st_dt).date()
get_first_day = datetime(year, month, st_dt).isoweekday()

def daterange(startDate, endDate, delta=timedelta(days=1)):
    currentDate = startDate
    while currentDate <= endDate:
        yield currentDate
        currentDate += delta

for date in daterange(date(year, month, st_dt), date(year, month, en_dt), delta=timedelta(days=1)):
     print(date)


  date.py 2020 5 1 31 # script

想出了一个独立的“if 循环”,正如我之前所说,不知道如何构建更大的图景:(

if get_first_day == 1:
        #print("Monday")
        sec_d =  first_date + timedelta(days=4)
elif get_first_day == 2:
        sec_d = first_date + timedelta(days=3)
elif get_first_day == 3:
        sec_d = first_date + timedelta(days=2)
elif get_first_day == 4:
        sec_d = first_date + timedelta(days=2)
elif get_first_day == 5:
        sec_d = first_date
        #print("Friday")
else:
        pass

print(f"Second date:{sec_d} ") -- which gave  -- > Second date:2020-05-01

最佳答案

您可以将日期保存在字典中,字典键是日历周和日期类型(周末、星期几)的元组。

每一天都保存在 allDays 字典中,并按 weeknum 和日期类型的组合作为键进行分组:

 ('18', 'weekend'): [datetime.date(2020, 5, 2), datetime.date(2020, 5, 3)],
 ('18', 'working'): [datetime.date(2020, 5, 1)],
 ('19', 'weekend'): [datetime.date(2020, 5, 9), datetime.date(2020, 5, 10)],
 ('19', 'working'): [datetime.date(2020, 5, 4), ...

所以你只需要取出每个字典项目的第一个和最后一个项目:

import sys
from datetime import date, datetime, timedelta

year, month, st_dt, en_dt = 2020, 5, 1, 31

first_date = datetime(year, month, st_dt).date()
get_first_day = datetime(year, month, st_dt).isoweekday()

def daterange(startDate, endDate, delta=timedelta(days=1)):
    currentDate = startDate
    while currentDate <= endDate:
        yield currentDate
        currentDate += delta

allDays = {}
_lastDayType = None
for dte in daterange(date(year, month, st_dt), date(year, month, en_dt), delta=timedelta(days=1)):
    if 0 <= dte.weekday() < 5:
        _dayType = 'working'
    else:
        _dayType = 'weekend'

    _weeknum = dte.strftime("%V")  # number of calendar week
    _key = (_weeknum, _dayType)
    if _key not in allDays:        # create an empty list if unique key doesnt exist
        allDays[_key] = []
    allDays[_key].append(dte)      # add the dates ...

for k,v in allDays.items():
    if len(v) == 1:
        first, last = v[0], v[0]
    else:
        first, last = v[0], v[-1]
    print("%s >> %s" % (first, last))

输出:

2020-05-01 >> 2020-05-01
2020-05-02 >> 2020-05-03
2020-05-04 >> 2020-05-08
2020-05-09 >> 2020-05-10
2020-05-11 >> 2020-05-15
2020-05-16 >> 2020-05-17
2020-05-18 >> 2020-05-22
2020-05-23 >> 2020-05-24
2020-05-25 >> 2020-05-29
2020-05-30 >> 2020-05-31

关于Python - 迭代月份日期并打印自定义输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62170155/

相关文章:

python - 在 Python 3 中将 CSV 文件附加到新的 CSV 文件时,单词之间出现不需要的 ""

python - 多种 ModelManager 过滤方法

python - 处理try-except block 内的错误后,Python处理错误

python - ElementTree 的替代 XML 解析器可以缓解 UTF-8 问题?

python - 为什么 Python 运行时以这种方式处理警告?

python-3.x - 如何将 Pandas 中的日历年转换为水年

gcc - 使用python3安装matplotlib时gcc出错

python - python中的图像尺寸错误

python - 在 django 项目中导入应用程序

python-3.x - 如何在 azure 机器学习工作室中保存和访问 pickle/hdf5 文件