search

Home  >  Q&A  >  body text

python - Question about calculating dates

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.

伊谢尔伦伊谢尔伦2714 days ago815

reply all(1)I'll reply

  • 代言

    代言2017-06-22 11:53:40

    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'))

    reply
    0
  • Cancelreply