dayofyear is not great when going into a new year

Chris Angelico rosuav at gmail.com
Tue Jan 5 17:53:40 EST 2021


On Wed, Jan 6, 2021 at 9:51 AM Michael F. Stemper <mstemper at gmail.com> wrote:
>
> On 05/01/2021 15.27, Chris Angelico wrote:
> > On Wed, Jan 6, 2021 at 8:02 AM Martin Schöön <martin.schoon at gmail.com> wrote:
>
> >> I have had some Python fun with COVID-19 data. I have done
> >> some curve fitting and to make that easier I have transformed
> >> date to day of year. Come end of 2020 and beginning of 2021
> >> and this idea falls on its face.
>
> > There are multiple definitions for "day of year", depending on how you
> > want to handle certain oddities. The simplest is to identify Jan 1st
> > as 1, Jan 2nd as 2, etc, to Dec 31st as either 365 or 366; but some
> > libraries will define the year as starting with the week that contains
> > the Thursday, or something, and then will define days of year
> > accordingly.
> >
> > If you want an easy way to graph day-by-day data and the exact day
> > numbers are irrelevant, what I'd recommend is: Convert the date into
> > Unix time, divide by 86400, floor it. That'll give you a Julian-style
> > date number where Jan 1st 1970 is 0, Jan 2nd is 1, etc, and at the end
> > of a year, it'll just keep on incrementing. That would get you past
> > the 2020/2021 boundary pretty smoothly.
>
> Possibly better than rolling your own is using standard stuff:
>
>  >>> from datetime import date,datetime
>  >>> datetime.toordinal(date(2020,1,1))
> 737425
>  >>> datetime.toordinal(date(2021,1,5))
> 737795
>  >>> datetime.toordinal(date(2021,1,5)) - datetime.toordinal(date(2020,1,1))
> 370
>  >>>
>

Oh yes. In fact, not "possibly", but "definitely" :) ALWAYS use a
library for date manipulation. But you have to know what you're doing
before you can figure out how to call on the library.

ChrisA


More information about the Python-list mailing list