代码之家  ›  专栏  ›  技术社区  ›  Blaž Čukelj

python错误的日期递增

  •  0
  • Blaž Čukelj  · 技术社区  · 6 年前

    我有个问题。我浏览股票网站。我有一个问题,当我增加日期。当我从2012年1月1日增加到2012年12月31日时,增量会很好地增加到2012年9月31日,但从1.10增加到2012年12月31日是错误的。代码如下:

    import datetime
    d = datetime.date(2012,1,1)
    for x in range(1,365):
        if d.day<10:
            dan = "0"+str(d.day)
        else:
            dan = d.day
    
        if d.month<10:
            mesec = "0"+str(d.month)
        else:
            month = str(d.month)
        leto= d.year
    
        print("http://www.ljse.si/cgi-bin/jve.cgi?doc=2561&subtab=0_2&date1="+str(dan)+"."+str(mesec)+"."+str(leto))
        print(str(d.day)+str(d.month)+str(d.year))
        d = d + datetime.timedelta(days=1)
    

    http://www.ljse.si/cgi-bin/jve.cgi?doc=2561&subtab=0_2&date1= 2012年9月29日

    期望输出: 2012年12月29日

    1 回复  |  直到 6 年前
        1
  •  1
  •   Patrick Artner    6 年前

    手动设置日期格式容易出错-您更改了变量的名称- month 从未用于创建URI和 mesec d.month > 9 . 请参阅@metatoaster的评论。

    strftime - date formatting :

    import datetime
    d = datetime.date(2012,1,1)
    
    # avoid off-by-1 leap-year mishaps due to hardcoded days/year
    while d.year < 2013:   
        # format as dd.mm.yyyy including leading 0 if need be
        dd = d.strftime("%d.%m.%Y")
        print("http://www.ljse.si/cgi-bin/jve.cgi?doc=2561&subtab=0_2&date1="+dd)
    
        d = d + datetime.timedelta(days=1)
    

    输出(用于 d = d + datetime.timedelta(days=36)

    http://www.ljse.si/cgi-bin/jve.cgi?doc=2561&subtab=0_2&date1=01.01.2012
    http://www.ljse.si/cgi-bin/jve.cgi?doc=2561&subtab=0_2&date1=06.02.2012
    http://www.ljse.si/cgi-bin/jve.cgi?doc=2561&subtab=0_2&date1=13.03.2012
    http://www.ljse.si/cgi-bin/jve.cgi?doc=2561&subtab=0_2&date1=18.04.2012
    http://www.ljse.si/cgi-bin/jve.cgi?doc=2561&subtab=0_2&date1=24.05.2012
    http://www.ljse.si/cgi-bin/jve.cgi?doc=2561&subtab=0_2&date1=29.06.2012
    http://www.ljse.si/cgi-bin/jve.cgi?doc=2561&subtab=0_2&date1=04.08.2012
    http://www.ljse.si/cgi-bin/jve.cgi?doc=2561&subtab=0_2&date1=09.09.2012
    http://www.ljse.si/cgi-bin/jve.cgi?doc=2561&subtab=0_2&date1=15.10.2012
    http://www.ljse.si/cgi-bin/jve.cgi?doc=2561&subtab=0_2&date1=20.11.2012
    http://www.ljse.si/cgi-bin/jve.cgi?doc=2561&subtab=0_2&date1=26.12.2012