Convert Year/Month/Day to Day of Year in Python
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.
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
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
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.