Created
July 4, 2018 08:38
-
-
Save sempr/187e7af6f105bcb698effa8bb077be32 to your computer and use it in GitHub Desktop.
new.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#coding:utf8 | |
def is_leap_year(y): | |
"""闰年判断 这样最快""" | |
return (y % 4 == 0) and (y % 100 != 0 or y % 400 == 0) | |
def leap_count(year): | |
"""从0年开始的闰年数量(不包含0年)""" | |
return year // 4 - year // 100 + year // 400 | |
def year_sum(year_start, year_end): | |
""" [ys, ye) 之间的天数 """ | |
return leap_count(year_end-1) - leap_count(year_start-1) + (year_end - year_start) * 365 | |
## prepare | |
### 每月天数 | |
d1 = (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) | |
### 累计天数 | |
ds1 = (None, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365) | |
### 每月天数 闰年 | |
d2 = (0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) | |
### 累计天数 闰年 | |
ds2 = (None, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366) | |
## prepare end | |
def get_days_by_ym(y, m): | |
# if m==2 and is_leap_year(y): | |
if (y % 4 == 0) and m==2 and (y % 100 != 0 or y % 400 == 0): | |
return 29 | |
return d1[m] | |
def get_day_count(y, m, d): | |
"""计算某年的某一天前有多少天,当天计入""" | |
if is_leap_year(y): | |
return ds2[m] + d | |
return ds1[m] + d | |
def my_function(y, m, d, n): | |
ny, nm = y + n // 12, m + n % 12 | |
if nm > 12: | |
ny += 1 | |
nm -= 12 | |
nd = min(get_days_by_ym(ny, nm), d) | |
# [y, ny) + nycount - ycount | |
return year_sum(y, ny) + get_day_count(ny, nm, nd) - get_day_count(y, m, d) | |
def my_function2(y, m, d, n): | |
ny, nm = y + n // 12, m + n % 12 | |
if nm > 12: | |
ny += 1 | |
nm -= 12 | |
nd = min(get_days_by_ym(ny, nm), d) | |
from datetime import datetime | |
return (datetime(ny, nm, nd) - datetime(y, m, d)).days | |
def my_test(): | |
dt = ( | |
(2016, 2, 29, 12, 365), | |
(2016, 2, 29, 48, 365*4+1), | |
(2016, 2, 29, 1, 29), | |
(2016, 1, 29, 12, 366), | |
(2016, 3, 29, 12, 365), | |
(2016, 1, 31, 1, 29), | |
(2017, 1, 31, 1, 28), | |
(2010, 3, 31, 1, 30), | |
(2000, 2, 29, 1200, 365*100+24), | |
(2001, 2, 28, 1200, 365*100+24), | |
(2000, 1, 31, 1, 29), | |
(2001, 1, 31, 1, 28), | |
(2000, 1, 28, 1, 31), | |
(2000, 1, 31, 48, 1461), | |
(2017, 1, 31, 3, 89), | |
(2000, 2, 29, 1200, 36524), | |
) | |
import time | |
s = time.time() | |
for rd in xrange(100000): | |
for y, m, d, n, r in dt: | |
nr = my_function(y, m, d, n) | |
print time.time() - s | |
if __name__ == "__main__": | |
my_test() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment