0

I have those data'. Year, Day of the year and it's a Leap year

Need to print "Month, Day" from given data.

year= 2020
day_oy= 357

I tried,

if day_ in range(1,32):
    new_month= "January"
elif day_ in range(32, 61):
    new_month= "February"

...

else:
    new_month= "December"

and it takes many lines. And I need to do it using minimum lines.

martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

0
import datetime

day_of_the_year = 357
year = 2020

datetime_object = datetime.datetime(year, 1, 1) + datetime.timedelta(day_of_the_year - 1)

# get month and day of the month

month = datetime_object.month
day_of_the_month = datetime_object.day

print(f"{day_of_the_month}/{month}")

Output:

22/12

Once you get the datetime object, you can get any details of the date in any format.

Refer to the below documentation for further details.

https://docs.python.org/3/library/datetime.html

Sumanth Lingappa
  • 464
  • 1
  • 6
  • 15
0

Based on this Q&A you probably want:

from datetime import datetime, timedelta

year = 2020
day_oy = 357

date = datetime(year=year, month=1, day=1)
date_oy = date + timedelta(days=day_oy - 1)
new_month = date_oy.strftime('%B')  # December
Kostas Mouratidis
  • 1,145
  • 2
  • 17
  • 30