# python写的获取一天从这一年开始的开数

2017-01-12 09:56:02来源:oschina作者:吕不为人点击

python写的获取一天从这一年开始的开数，当然，如果用python的内置函数，一行代码就OK了。

#!/usr/bin/env python3 month1 = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] month2 = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] def leapyear(year): return (year % 4 == 0 and (year % 100 != 0)) or (year % 400 == 0) def dayOfYear(year, month, day): _month = month2 if leapyear(year) else month1 return sum(_month[:month-1]) + day - 1 if __name__ == '__main__': print(dayOfYear(2014, 3, 1))

import unittest import rn import datetime

class Test1(unittest.TestCase): def test_yn1(self): assert rn.leapyear(2001) == False assert rn.leapyear(2002) == False assert rn.leapyear(2003) == False assert rn.leapyear(2004) == Truedef test1(self): t1 = (datetime.date(2017, 1, 10) - datetime.date(2017, 1, 1)).days t2 = rn.dayOfYear(2017, 1, 10) assert t1 == t2

def test2(self): t1 = (datetime.date(2017, 3, 10) - datetime.date(2017, 1, 1)).days t2 = rn.dayOfYear(2017, 3, 10) assert t1 == t2 def test3(self): t1 = (datetime.date(2004, 3, 1) - datetime.date(2004, 1, 1)).days t2 = rn.dayOfYear(2004, 3, 1) assert t1 == t2

def testall(self): _date = datetime.date(2000, 1, 1).toordinal() for i in range(1000000):_date += 1_newdate = datetime.date.fromordinal(_date)_yearbegin = datetime.date(_newdate.year, 1, 1)t1 = (_newdate - _yearbegin).dayst2 = rn.dayOfYear(_newdate.year, _newdate.month, _newdate.day)assert t1 == t2 if __name__ == '__main__': unittest.main()