Home > Software design >  How to convert the integer day of year into the format mm/dd in python
How to convert the integer day of year into the format mm/dd in python

Time:09-22

Given a day of the year, say 32. How can I convert this number into the format mm/dd? For example 32 would be 02/01.

The year is not necessary because my objective is to find what the average day of the year x occurs.

CodePudding user response:

from datetime import datetime

day_num = "32"

day_num.rjust(3   len(day_num), '0')
year = "2020"

date_format = "%m-%d-%Y"
res = datetime.strptime(year   "-"   day_num, "%Y-%j").strftime(date_format)
print("Resolved date : "   str(res))

If you want to only print the month and the day, set the date_format to %m/%d

CodePudding user response:

from datetime import datetime
  
# initialise the day number in string
day_num = '32'
  
# adjust the day number
day_num.rjust(3   len(day_num), '0')
  
# Initialise the year in string
year = '2021'
  
# convert to date
res = datetime.strptime(year   "-"   day_num, "%Y-%j").strftime("%m-%d-%Y")
  
# printing result
print("Resolved date : "   str(res))

output:

Resolved date : 02-01-2021

CodePudding user response:

Try this:

from calendar import monthrange
from datetime import date


days_per_month = [monthrange(date.min.year, n)[1] for n in range(1, 13)]


def formatted_month_date(n: int) -> str:
    month = day = 0
    for i, days in enumerate(days_per_month):
        if n > days:
            n -= days
        else:
            month = i   1
            day = n
            break

    d = date(date.min.year, month, day)
    return d.strftime('%m/%d')


print(formatted_month_date(32))
print(formatted_month_date(59))
  • Related