Get date object for the first/last day of the current year
The only real improvement that comes to mind is to give your variables more descriptive names than a
and b
.
You'll have some funky stuff going on if you happen to be running this late on New Year's Eve and the two calls to today()
cross the year boundary. It's safer to do this:
from datetime import date
epoch_year = date.today().year
year_start = date(epoch_year, 1, 1)
year_end = date(epoch_year, 12, 31)
There is nothing in the python library but there are external libraries that wrap this functionality up. For example, pandas
has a timeseries library, with which you can do:
from datetime import date
from pandas.tseries import offsets
a = date.today() - offsets.YearBegin()
b = date.today() + offsets.YearEnd()
Whilst pandas
is overkill if all you want is year begin and year end functionality, it also has support for a lot of other high level concepts such as business days, holiday calendars, month/quarter/year offsets: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#dateoffset-objects
from datetime import datetime
starting_day_of_current_year = datetime.now().date().replace(month=1, day=1)
ending_day_of_current_year = datetime.now().date().replace(month=12, day=31)