196

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

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

and I would like to compute the day of year that takes leap years into account. e.g. today (March 6, 2009) is the 65th day of 2009.

I see a two options:

  1. Create a number_of_days_in_month = [31, 28, ...] array, decide if it's a leap year and manually sum up the days.

  2. Use datetime.timedelta to make a guess & then binary search for the correct day of the year:

    >>> import datetime
    >>> YEAR = 2009
    >>> DAY_OF_YEAR = 62
    >>> d = datetime.date(YEAR, 1, 1) + datetime.timedelta(DAY_OF_YEAR - 1)
    

These both feel pretty clunky & I have a gut feeling that there's a more "Pythonic" way of calculating the day of the year. Any ideas/suggestions?

7 Answers 7

370

Use datetime.timetuple() to convert your datetime object to a time.struct_time object then get its tm_yday property:

from datetime import datetime
day_of_year = datetime.now().timetuple().tm_yday  # returns 1 for January 1st
4
  • 20
    A very minor and arguably pedantic addition, but using date.today() rather than datetime.now() also works and emphasizes the nature of the operation a bit more.
    – Jeremy
    Commented Dec 30, 2013 at 6:57
  • 8
    note: this starts counting at 1 Commented Nov 21, 2019 at 10:20
  • 3
    what if i want to do the reverse, I have the number lets say "26th day of the year 2020", and I want to have it converted into a date "26-01-2020"?
    – Sankar
    Commented Jan 26, 2020 at 6:51
  • 5
    @Sankar then you google for that question and ask your own Stack Overflow question if you don't find anything.
    – user3064538
    Commented Nov 1, 2020 at 15:58
70

You could use strftime with a %j format string:

>>> import datetime
>>> today = datetime.datetime.now()
>>> today.strftime('%j')
'065'

but if you wish to do comparisons or calculations with this number, you would have to convert it to int() because strftime() returns a string. If that is the case, you are better off using DzinX's answer.

2
  • 3
    Using strftime is indirect, because it produces a string from a number: the timetuple.tm_yday member. Read the source. The produced string should be converted to a number before any calculations/comparisons, so why bother?
    – tzot
    Commented Mar 8, 2009 at 13:52
  • 4
    If one needed the day of year in a string, say for use in a file name, than strftime is a much cleaner solution.
    – captain_M
    Commented Nov 14, 2014 at 21:18
17

DZinX's answer is a great answer for the question. I found this question and used DZinX's answer while looking for the inverse function: convert dates with the julian day-of-year into the datetimes.

I found this to work:

import datetime
datetime.datetime.strptime('1936-077T13:14:15','%Y-%jT%H:%M:%S')

>>>> datetime.datetime(1936, 3, 17, 13, 14, 15)

datetime.datetime.strptime('1936-077T13:14:15','%Y-%jT%H:%M:%S').timetuple().tm_yday

>>>> 77

Or numerically:

import datetime
year,julian = [1936,77]
datetime.datetime(year, 1, 1)+datetime.timedelta(days=julian -1)

>>>> datetime.datetime(1936, 3, 17, 0, 0)

Or with fractional 1-based jdates popular in some domains:

jdate_frac = (datetime.datetime(1936, 3, 17, 13, 14, 15)-datetime.datetime(1936, 1, 1)).total_seconds()/86400+1
display(jdate_frac)

>>>> 77.5515625

year,julian = [1936,jdate_frac]
display(datetime.datetime(year, 1, 1)+datetime.timedelta(days=julian -1))

>>>> datetime.datetime(1936, 3, 17, 13, 14, 15)

I'm not sure of etiquette around here, but I thought a pointer to the inverse functionality might be useful for others like me.

12

If you have reason to avoid the use of the datetime module, then these functions will work.

def is_leap_year(year):
    """ if year is a leap year return True
        else return False """
    if year % 100 == 0:
        return year % 400 == 0
    return year % 4 == 0

def doy(Y,M,D):
    """ given year, month, day return day of year
        Astronomical Algorithms, Jean Meeus, 2d ed, 1998, chap 7 """
    if is_leap_year(Y):
        K = 1
    else:
        K = 2
    N = int((275 * M) / 9.0) - K * int((M + 9) / 12.0) + D - 30
    return N

def ymd(Y,N):
    """ given year = Y and day of year = N, return year, month, day
        Astronomical Algorithms, Jean Meeus, 2d ed, 1998, chap 7 """    
    if is_leap_year(Y):
        K = 1
    else:
        K = 2
    M = int((9 * (K + N)) / 275.0 + 0.98)
    if N < 32:
        M = 1
    D = N - int((275 * M) / 9.0) + K * int((M + 9) / 12.0) + 30
    return Y, M, D
1
  • Useful when d,m,y are separately present! Commented Jan 30, 2022 at 3:11
9

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 + 1
2
  • 1
    How did you calculate the performance? I tried using time.time and those are my results: def f(): (today - datetime.datetime(today.year, 1, 1)).days + 1 start = time.time(); f(); print('Lapsed {}'.format( time.time() - start)); Lapsed 5.221366882324219e-05 def f(): int(today.strftime('%j')); start = time.time(); f(); print('Lapsed {}'.format( time.time() - start)); Lapsed 7.462501525878906e-05
    – ssoto
    Commented Aug 22, 2017 at 11:16
  • 1
    Need a + 1 in the last line. Should be yday = (period_end - date(period_end.year, 1, 1)).days + 1. Commented Jun 28, 2022 at 20:43
5

Just subtract january 1 from the date:

import datetime
today = datetime.datetime.now()
day_of_year = (today - datetime.datetime(today.year, 1, 1)).days + 1
1
  • 2
    d.toordinal() - date(d.year, 1, 1).toordinal() + 1 is more standard according to the documentation. It is equivalent to the accepted answer without producing the whole time tuple.
    – Dingle
    Commented Apr 30, 2010 at 19:52
2

You may simple use dayofyear attribute provided by "pandas" which in turn give you the day of the year for a particular year. For e.g.

data["day_of_year"] = data.Datetime.apply(lambda x:x.dayofyear)

1
  • 1
    The question doesn't mention pandas, though. Commented Oct 24, 2023 at 9:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.