I need to get date
objects for the first and last day in the current year.
Currently I'm using this code which works fine, but I'm curious if there's a nicer way to do it; e.g. without having to specify the month/day manually.
from datetime import date
a = date(date.today().year, 1, 1)
b = date(date.today().year, 12, 31)
The only real improvement that comes to mind is to give your variables more descriptive names than a
and b
.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With