Interpret YYYYMMDD as the nth day of the year I am provided a bunch of dates in the format (YYYYMMDD) such as:

date='20170503'


My goal is to convert that date into the number of days in the given year. For example, it would convert:


20170130 to 30
20170201 to 32
20151231 to 365


Here is my solution:

import pandas as pd
my_date = pd.to_datetime(date, format='%Y%m%d')
my_ordinal = 736329 - 365*(2017 - my_date.year)
print(datetime.toordinal(my_date) - my_ordinal)


Is there a better way to do this without making it much more complex? Note that pandas is already in the program, so there is no extra burden in using it.
As you already use pandas, you are right that there is no overhead on using Timestamps (the kind of objects returned by pd.to_datetime). But, as said in the documentation (help(pd.Timestamp)):


  Help on class Timestamp in module pandas.tslib:
  
  class Timestamp(_Timestamp)
 |  TimeStamp is the pandas equivalent of python's Datetime
 |  and is interchangable with it in most cases. It's the type used
 |  for the entries that make up a DatetimeIndex, and other timeseries
 |  oriented data structures in pandas.



So you may choose pd.Timestamp or Python's datetime.datetime interchangeably.

The simplest way to count days from January 1st of the same year is to build both objects and then substract each other to get the count of days separating them. Take care of adding one day to actually count January 1st as well:

date = pd.to_datetime('20170201', format='%Y%m%d')
new_year_day = pd.Timestamp(year=date.year, month=1, day=1)
day_of_the_year = (date - new_year_day).days + 1


Now, having this piece of code hanging around is not really of any use, so you should wrap it into a function for better reusability:

import pandas as pd


def date_to_nth_day(date, format='%Y%m%d'):
    date = pd.to_datetime(date, format=format)
    new_year_day = pd.Timestamp(year=date.year, month=1, day=1)
    return (date - new_year_day).days + 1


if __name__ == '__main__':
    print(date_to_nth_day('20170201'))


Using Python's datetime module, the function would look like:

def date_to_nth_day(date, format='%Y%m%d'):
    date = datetime.datetime.strptime(date, format=format)
    new_year_day = datetime.datetime(year=date.year, month=1, day=1)
    return (date - new_year_day).days + 1