Extract day of year and Julian day from a string date

前端 未结 9 2020
臣服心动
臣服心动 2020-11-27 06:51

I have a string \"2012.11.07\" in python. I need to convert it to date object and then get an integer value of day of year and also Julian day

9条回答
  •  温柔的废话
    2020-11-27 07:02

    To get the Julian day, use the datetime.date.toordinal method and add a fixed offset.

    The Julian day is the number of days since January 1, 4713 BC at 12:00 in the proleptic Julian calendar, or November 24, 4714 BC at 12:00 in the proleptic Gregorian calendar. Note that each Julian day starts at noon, not midnight.

    The toordinal function returns the number of days since December 31, 1 BC at 00:00 in the proleptic Gregorian calendar (in other words, January 1, 1 AD at 00:00 is the start of day 1, not day 0). Note that 1 BC directly precedes 1 AD, there was no year 0 since the number zero wasn't invented until many centuries later.

    import datetime
    
    datetime.date(1,1,1).toordinal()
    # 1
    

    Simply add 1721424.5 to the result of toordinal to get the Julian day.

    Another answer already explained how to parse the string you started with and turn it into a datetime.date object. So you can find the Julian day as follows:

    import datetime
    
    my_date = datetime.date(2012,11,7)   # time = 00:00:00
    my_date.toordinal() + 1721424.5
    # 2456238.5
    

提交回复
热议问题