在Python中将小数年转换为实际日期

时间:2013-10-10 20:51:48

标签: python

如何使用python将小数年转换为实际日期? E. g。我有一个包含分数年的数组[2012.343,2012.444,2012.509],我想得到“yyyy-mm-dd hh:mm”。

3 个答案:

答案 0 :(得分:7)

这是一个更好的解决方案,以日期时间格式为您提供答案。

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

此解决方案不计算闰年的额外日期。如果您需要这样做,请创建一个返回bool的函数is_leap(year),并将我的代码更改为:

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

结帐datetime module。您可以在那里找到更好的解决方案。

答案 1 :(得分:3)

import datetime as DT
def t2dt(atime):
    """
    Convert atime (a float) to DT.datetime
    This is the inverse of dt2t.
    assert dt2t(t2dt(atime)) == atime
    """
    year = int(atime)
    remainder = atime - year
    boy = DT.datetime(year, 1, 1)
    eoy = DT.datetime(year + 1, 1, 1)
    seconds = remainder * (eoy - boy).total_seconds()
    return boy + DT.timedelta(seconds=seconds)

def dt2t(adatetime):
    """
    Convert adatetime into a float. The integer part of the float should
    represent the year.
    Order should be preserved. If adate<bdate, then d2t(adate)<d2t(bdate)
    time distances should be preserved: If bdate-adate=ddate-cdate then
    dt2t(bdate)-dt2t(adate) = dt2t(ddate)-dt2t(cdate)
    """
    year = adatetime.year
    boy = DT.datetime(year, 1, 1)
    eoy = DT.datetime(year + 1, 1, 1)
    return year + ((adatetime - boy).total_seconds() / ((eoy - boy).total_seconds()))

答案 2 :(得分:0)

您可以确定年份1月1日的纪元时间。将其添加到小数部分时间365 * 24 * 60 * 60.然后将您的纪元时间转换为日期时间。

请参阅Python: Converting Epoch time into the datetime