Search code examples
pythonpython-2.7python-datetime

How to get relevant month and date by inputting only the day of year in python


I'm developing a phonebook application from python as a mini project in which I'm having the requirement to store the NIC number of a person and then display his/her gender, DOB and age. I have to derive these 3 information and I'm able to derive the gender, but I don't know how to derive the DOB - only the birth year because the NIC number's first 2 digits represent the year of birth.

In a NIC number, the 3rd three digits are the day of year :- from 001 to 366. I can seperate those 3 digits to another variable as well, but how do I derive the month and the date of month which it refers to?

For example :

derivedYear = 1996
dayOfYear = 032

finalDOB = "1996.02.01"
print finalDOB

I want to know how to calculate the finalDOB value. I'm using python 2.7.6


Solution

  • You can use %j format for day of year in datetime.datetime.strptime() , to get the corresponding datetime object . Example -

    >>> derivedYear = 1996
    >>> dayOfYear = 32
    >>> import datetime
    >>> d = datetime.datetime.strptime('{} {}'.format(dayOfYear, derivedYear),'%j %Y')
    >>> d
    datetime.datetime(1996, 2, 1, 0, 0)
    

    Then you can use the .day and .month attribute of the datetime object to get the corresponding day and month. Example -

    >>> d.day
    1
    >>> d.month
    2
    

    If you want the result in format - YYYY.MM.DD - you can use strftime() and supply the format to it. Example -

    >>> d.strftime('%Y.%m.%d')
    '1996.02.01'
    

    Also, please note, you should not define your dayOfYear with a leading 0 , as that would make the literal an octal number, which would not be what you want.