Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert fractional years to a real date in Python

Tags:

python

How do I convert fractional years to a real date by using python? E. g. I have an array [2012.343, 2012.444, 2012.509] containing fractional years and I would like to get "yyyy-mm-dd hh:mm".

like image 630
paulchen Avatar asked Oct 10 '13 20:10

paulchen


1 Answers

Here it`s a better solution, that give you the answer in datetime format.

from datetime import timedelta, datetime

def convert_partial_year(number):

    year = int(number)
    d = timedelta(days=(number - year)*365)
    day_one = datetime(year,1,1)
    date = d + day_one
    return date

This solution doesnt count the extra day in leap years. If you need to do so, make a function is_leap(year) that returns a bool, and change my code to this:

from datetime import timedelta, datetime

def convert_partial_year(number):

    year = int(number)
    d = timedelta(days=(number - year)*(365 + is_leap(year)))
    day_one = datetime(year,1,1)
    date = d + day_one
    return date

Check out datetime module. You can find a even better solution for your problem there.

like image 197
Lucas Ribeiro Avatar answered Nov 15 '22 12:11

Lucas Ribeiro