在python中打印特定日期

时间:2018-01-15 09:42:46

标签: python

我想创建一个根据每个月返回日期的函数。更具体的我希望它以示例格式(YYYY,MM,DD)返回给我每个月的第23天:
2018, 1, 23

除了这个日期与周末同时发生的情况,我希望它返回前一个工作日。例如2017年12月23日是星期六,所以在这种情况下我想让我的功能回到我身边 2017, 12, 22

现在我使用:

import datetime
someday = datetime.date(2018, 1, 23)
    print(someday)

someday变量中,我为每个月手动定义了所需的日期。

简而言之,即2018年的未来七个月(1月,2月,3月,4月,5月,6月,7月),我希望我的功能能够归还给我:

2018, 1, 23
2018, 2, 23
2018, 3, 23
2018, 4, 23
2018, 5, 23
2018, 6, 22
2018, 7, 23

以后等等等等。

2 个答案:

答案 0 :(得分:1)

我写了一个关于你如何做的小蟒蛇脚本。

使用toordinal检查星期几,如果是星期六或星期日,请使用timedelta

减1或2
import datetime

# Yes, from 1,13 because 13 is exclusive (Goes only to 12)
days_month = datetime.monthrange(2018,x)
for x in range(days_month[0],days_month[1]+1):
    for x in range(1, monthrange):
        someday = datetime.date(2018, x, 23) # Loop over every month
        weekday = someday.weekday() # 0 = Monday, 6 = Sunday
        if(weekday > 5 ): # If it's "more" than Friday
            jumpback_days = weekday - 4; # Subtract 4 from the current weekday to get 1 for Saturday and 2 for Sunday
            print(someday - datetime.timedelta(days=jumpback_days)) # Subtract days and print
        else:
            # Print without subtracting anything
            print(someday)

注意:如果您使用的是Python2,请将range替换为xrange,以便它可以正常使用。

编辑:如果您想在特定年份打印所有工作日,您可以这样做:

import datetime
from calendar import monthrange

year = 2018
for month in range(1, 13): # Yes, from 1,13 because 13 is exclusive (Goes only to 12)
    days_month = monthrange(year, month) # Request the amount of days in that month
    for day in range(1, days_month[1] + 1): # Iterate through all days of that month (+1 because it's exclusive)
        someday = datetime.date(year, month, day) # Loop over every month
        weekday = someday.weekday() # 0 = Monday, 6 = Sunday
        if(weekday < 5 ): # If it's "less" than Saturday
            # Print because if it's "less" than Saturday, then it's a workday
            print(someday)

答案 1 :(得分:1)

您可以使用weekday()timedelta()while循环实现此目的:

from datetime import date, timedelta

def last_workday(somedate):
    while somedate.weekday() > 4: #weekday returns values 0-6 (Mon-Sun)
        somedate -= timedelta(days=1) #timedelta returns 1 day which you subtract from your date 
    return somedate

y = 2018
d = 23

for m in range(1,13):
    print(last_workday(date(y, m, d)))