How to convert Python datetime dates to decimal/float years

前端 未结 7 1377
感动是毒
感动是毒 2020-12-09 18:18

I am looking for a way to convert datetime objects to decimal(/float) year, including fractional part. Example:

>>> obj = SomeObjet()
>>> o         


        
7条回答
  •  -上瘾入骨i
    2020-12-09 19:02

    I'm assuming that you are using this to compare datetime values. To do that, please use the the timedelta objects instead of reiniventing the wheel.

    Example:

    >>> from datetime import timedelta
    >>> from datetime import datetime as dt
    >>> d = dt.now()
    >>> year = timedelta(days=365)
    >>> tomorrow = d + timedelta(days=1)
    >>> tomorrow + year > d + year
    True
    

    If for some reason you truly need decimal years, datetime objects method strftime() can give you an integer representation of day of the year if asked for %j - if this is what you are looking for, see below for a simple sample (only on 1 day resolution):

    >>> from datetime import datetime
    >>> d = datetime(2007, 4, 14, 11, 42, 50)
    >>> (float(d.strftime("%j"))-1) / 366 + float(d.strftime("%Y"))
    2007.2814207650274
    

提交回复
热议问题