如何将任何日期转换为仅几天?这就是我尝试的:
import datetime
import calendar
def leap_day_counter(yr):
leap_days = 0
# since 1582 11 days are missing
if yr >= 1582:
leap_days += 11
for specific_year in range(1, yr):
if calendar.isleap(specific_year):
leap_days += 1
return leap_days
def month_to_day(yr, mth):
all_days = 0
for specific_month in range(1, mth+1):
days_in_month = calendar.monthrange(yr, specific_month)
all_days += days_in_month[1]
return all_days
date = datetime.datetime.now()
days_passed = ((date.year * 365) + leap_day_counter(date.year)) + month_to_day(date.year, date.month) + date.day
print(days_passed)
我有737 158天,但根据https://www.timeanddate.com/date/durationrationresult.html,我应该有736 755天。我想念什么吗?是否可以更轻松地这样做?
这有帮助
from datetime import date
d0 = date(2000, 1, 01)
d1 = date.today()
delta = d1 - d0
print delta.days
-
一年中的天数对您来说是正确的吗?
01/01/0001-01/01/2018有736,696,您说有737,060。这大约是1年。
(date.year - 1) * 365
-
修复上述内容后,我们应该检查01/01/0001-01/02/2018是否有效。
该网站说736,727,您说736,754。这大约是整个2月太多的月份。
for specific_month in range(1, mth)
-
您有太多的leap年。
for specific_year in range(1, yr)
您还可以将此代码简化为:
def leap_day_counter(y): y -= 1 return y//4 - y//100 + y//400
现在与datetime.datetime.now().toordinal()
相同。
两个日期之间的天数如下:有关更多信息,请参见此处。希望这可能会有所帮助
>>>enddate = "2018/03/12" +" 23:59"
>>>enddate = datetime.strptime(enddate, "%Y/%m/%d %H:%M")
>>>(enddate-datetime.now()).days
12
更新:编辑
>>>import datetime
>>>checkdate = datetime.datetime.strptime("0001-01-01", "%Y-%m-%d")
>>>days = (datetime.datetime.now()-checkdate).days
>>>days
736757
2天的差异,因为不包括开始日期和结束日期。