How to calculate number of days between two given dates?

前端 未结 13 1492
梦如初夏
梦如初夏 2020-11-22 06:29

If I have two dates (ex. \'8/18/2008\' and \'9/26/2008\'), what is the best way to get the number of days between these two dates?

13条回答
  •  深忆病人
    2020-11-22 06:54

    There is also a datetime.toordinal() method that was not mentioned yet:

    import datetime
    print(datetime.date(2008,9,26).toordinal() - datetime.date(2008,8,18).toordinal())  # 39
    

    https://docs.python.org/3/library/datetime.html#datetime.date.toordinal

    date.toordinal()

    Return the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1. For any date object d, date.fromordinal(d.toordinal()) == d.

    Seems well suited for calculating days difference, though not as readable as timedelta.days.

提交回复
热议问题