python - Question about calculating dates
伊谢尔伦
伊谢尔伦 2017-06-22 11:51:40
0
1
776

Code first

def get_date(today,num):

    try:

        myday = datetime.datetime( int(today[0:4]),int(today[5:7]),int(today[8:10]) ) + datetime.timedelta(days=num)

        dt = myday.strftime('%Y-%m-%d')

    except Exception as e:

        print(e)

        print('日期格式不合法')

        return

    return dt
if __name__=='__main__':

    print('计算日期列表...')

    date_list=[]

    today='2017-06-20'

    for i in range(-90,0):

        date=get_date(today,i)

        ISOTIMEFORMAT = '%Y-%m-%d'

        tm=time.strptime(date, ISOTIMEFORMAT)

        if time.asctime(tm)[0:3]!='Sat' and time.asctime(tm)[0:3]!='Sun':

            date_list.append(date)#去除双休日

        else:

            print date,'is holiday,removed..'

    #date_list就是日期列表

The calculation is for all dates in the 90 days before 2017-6-20 except weekends. Does anyone have a simpler and more violent method? Third-party libraries are also recommended.

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(1)
代言
from datetime import datetime, timedelta

def get_date(today):
    date_format = '%Y-%m-%d'
    dt = datetime.strptime(today, date_format)
    for i in range(1, 91):
        dt = dt + timedelta(days=-1)
        if dt.weekday() > 0 and dt.weekday() < 6:
            yield dt.strftime(date_format)

print list(get_date('2017-06-20'))
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!