Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get date object for the first/last day of the current year

Tags:

python

date

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)
like image 452
ThiefMaster Avatar asked Mar 24 '11 10:03

ThiefMaster


3 Answers

The only real improvement that comes to mind is to give your variables more descriptive names than a and b.

like image 50
NPE Avatar answered Nov 09 '22 16:11

NPE


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)
like image 24
Ibrohim Ermatov Avatar answered Nov 09 '22 17:11

Ibrohim Ermatov


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

like image 9
danio Avatar answered Nov 09 '22 18:11

danio