Is there a simple way to import into my Python file a list with all the dates for a given year?
What I need is to store everyday that a year has (01.01.2018----31.12.2018) into a list, so I can then import this list into a column in a table in a SQL database.
I have been Google for hours and didn´t find anything but there should be a way to import this directly...
Anyone knows? Thanks a lot!
This seems a bit cleaner for what he's looking for and it's a one-liner!
import datetimeyear = 2018
datelist = [d for d in range(datetime.date(year,12,31)-datetime.date(year,1,1)).days)]
This will result in datelist
being a list
from [1, 2, 3, ... 365/366]
.
Edit Added Patrick's suggestion and correct formatting as required
All you will need to do to get the format you want would be to get the date from the number explained here and format it correctly. which can also be done in one line but it's a little much for some.
datelist = [datetime.fromordinal(date(year, 1, 1).toordinal() + d - 1).strftime("dd.mm.yyyy") for d in range(1,365+ 1 if isLeap(year) else 0))]
Broken down, here's the long way of the above:
datelist = []
for d in range(1,365+ 1 if isLeap(year) else 0):day = datetime.fromordinal(date(year, 1, 1).toordinal() + d - 1)datelist.append(day.strftime("dd.mm.yyyy"))
This results in a list looking like:
["01.01.2018", "02.01.2018", ... "31.12.2018"]