Convert Year/Month/Day to Day of Year in Python

前端 未结 6 1656
不知归路
不知归路 2020-11-29 17:32

I\'m using the datetime module, i.e.:

>>> import datetime
>>> today = datetime.datetime.now()
>>> print(today)
2009-03-06 13:24:58.         


        
6条回答
  •  迷失自我
    2020-11-29 17:48

    I want to present performance of different approaches, on Python 3.4, Linux x64. Excerpt from line profiler:

          Line #      Hits         Time  Per Hit   % Time  Line Contents
          ==============================================================
             (...)
             823      1508        11334      7.5     41.6          yday = int(period_end.strftime('%j'))
             824      1508         2492      1.7      9.1          yday = period_end.toordinal() - date(period_end.year, 1, 1).toordinal() + 1
             825      1508         1852      1.2      6.8          yday = (period_end - date(period_end.year, 1, 1)).days + 1
             826      1508         5078      3.4     18.6          yday = period_end.timetuple().tm_yday
             (...)
    

    So most efficient is

    yday = (period_end - date(period_end.year, 1, 1)).days
    

提交回复
热议问题