2

Possible Duplicate:
Python Question: Year and Day of Year to date?

Is there a method in Python to figure out which month a certain day of the year is in, e.g. today is day 299 (October 26th). I would like to figure out, that day 299 is in month 10 (to compile the string to set the Linux system time). How can I do this?

Community
  • 1
  • 1
stdcerr
  • 13,725
  • 25
  • 71
  • 128

2 Answers2

3
print (datetime.datetime(2012,1,1) + datetime.timedelta(days=299)).month

Here's a little more usable version that returns both the month and day:

def get_month_day(year, day, one_based=False):
    if one_based:  # if Jan 1st is 1 instead of 0
        day -= 1
    dt = datetime.datetime(year, 1, 1) + datetime.timedelta(days=day)
    return dt.month, dt.day

>>> get_month_day(2012, 299)
(10, 26)
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
1

I know of no such method, but you can do it like this:

print datetime.datetime.strptime('2012 299', '%Y %j').month

The above prints 10

rantanplan
  • 7,283
  • 1
  • 24
  • 45