Convert Year/Month/Day to Day of Year in Python

前端 未结 6 1665
不知归路
不知归路 2020-11-29 17:32

I\'m using the datetime module, i.e.:

>>> import datetime
>>> today = datetime.datetime.now()
>>> print(today)
2009-03-06 13:24:58.         


        
6条回答
  •  伪装坚强ぢ
    2020-11-29 17:40

    DZinX's answer is a great answer for the question. I found this question and used DZinX's answer while looking for the inverse function: convert dates with the julian day-of-year into the datetimes.

    I found this to work:

    import datetime
    datetime.datetime.strptime('1936-077T13:14:15','%Y-%jT%H:%M:%S')
    
    >>>> datetime.datetime(1936, 3, 17, 13, 14, 15)
    
    datetime.datetime.strptime('1936-077T13:14:15','%Y-%jT%H:%M:%S').timetuple().tm_yday
    
    >>>> 77
    

    Or numerically:

    import datetime
    year,julian = [1936,77]
    datetime.datetime(year, 1, 1)+datetime.timedelta(days=julian -1)
    
    >>>> datetime.datetime(1936, 3, 17, 0, 0)
    

    Or with fractional 1-based jdates popular in some domains:

    jdate_frac = (datetime.datetime(1936, 3, 17, 13, 14, 15)-datetime.datetime(1936, 1, 1)).total_seconds()/86400+1
    display(jdate_frac)
    
    >>>> 77.5515625
    
    year,julian = [1936,jdate_frac]
    display(datetime.datetime(year, 1, 1)+datetime.timedelta(days=julian -1))
    
    >>>> datetime.datetime(1936, 3, 17, 13, 14, 15)
    

    I'm not sure of etiquette around here, but I thought a pointer to the inverse functionality might be useful for others like me.

提交回复
热议问题