Pythonic difference between two dates in years?

后端 未结 12 2515
醉酒成梦
醉酒成梦 2020-12-02 16:21

Is there a more efficient way of doing this below? I want to have the difference in years between two dates as a single scalar. Any suggestions are welcome.

         


        
12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-02 17:16

    Since we're coming to the end of 2018...

    from dateutil import parser
    from dateutil.relativedelta import relativedelta
    
    rip = [
        ["Tim Bergling\t\t",         " 8 Sep 1989", "20 Apr 2018"], # Avicii Swedish musician
        ["Stephen Hillenburg\t",     "21 Aug 1961", "26 Nov 2018"], # Creator of Spongebob
        ["Stephen Hawking\t\t",      " 8 Jan 1942", "14 Mar 2018"], # Theoretical physicist
        ["Stan Lee\t\t",             "28 Dec 1922", "12 Nov 2018"], # American comic book writer
        ["Stefán Karl Stefánsson\t", "10 Jul 1975", "21 Aug 2018"]  # Robbie Rotten from LazyTown
        ]
    
    for name,born,died in rip:
        print("%s %s\t %s\t died at %i"%(name,born,died,relativedelta(parser.parse(died),parser.parse(born)).years))
    

    output

    Tim Bergling              8 Sep 1989     20 Apr 2018     died at 28
    Stephen Hillenburg       21 Aug 1961     26 Nov 2018     died at 57
    Stephen Hawking           8 Jan 1942     14 Mar 2018     died at 76
    Stan Lee                 28 Dec 1922     12 Nov 2018     died at 95
    Stefán Karl Stefánsson   10 Jul 1975     21 Aug 2018     died at 43
    

提交回复
热议问题