Import everyday date for one year

2019-09-22 12:08发布

问题:

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!

回答1:

This seems a bit cleaner for what he's looking for and it's a one-liner!

import datetime

year = 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"]


回答2:

With Sqlite, you can do this directly in SQL, no python needed, thanks to recursive CTEs:

CREATE TABLE days(day TEXT PRIMARY KEY) WITHOUT ROWID;
INSERT INTO days(day)
  WITH RECURSIVE alldays(day) AS
       (VALUES ('2018-01-01')
        UNION ALL
        SELECT date(day, '+1 day')
        FROM alldays
        LIMIT 366 -- Take leap years into account
       )
  SELECT day FROM alldays WHERE day <= '2018-12-31';
-- List days in October:
SELECT day FROM days WHERE day BETWEEN '2018-10-01' AND '2018-10-31' ORDER BY day;


回答3:

from datetime import date
from datetime import timedelta

#get starting date 01.01.2018
startingDate = date(date.today().year, 1, 1)
currentDate = startingDate
for _ in range(365):
    print(currentDate.strftime('%m.%d.%Y'))
    #get next day
    currentDate = currentDate + timedelta(days=1)


回答4:

You can start with a datetime of 2018-1-1 and add a range of 0 to 364/365 days to that:

import datetime

def getDays(year):
    """Generates all days in one year, respecting leap years. Uses Gregorian
    calendarso best keep the year post 1582."""
    def isLeap(y):
        return y%4 == 0 and ( not y % 100 == 0 or y % 400 == 0)

    dt = datetime.date(year,1,1)
    days = 365 + (1 if isLeap(dt.year) else 0) # needs the (..) due to operator precedence

    return (dt + datetime.timedelta(days=k) for k in range( days ) ) 

print(list(getDays(2018)))

Output:

[datetime.date(2018, 1, 1), datetime.date(2018, 1, 2), datetime.date(2018, 1, 3), ..., 
 datetime.date(2018, 12, 29), datetime.date(2018, 12, 30), datetime.date(2018, 12, 31)]

Leapyears:

for y in [1900,2000]:
    d = list(getDays(y))
    print(d[58:60], d[-1:])

Ouput:

# 1900 - not a leap yeaer
[datetime.date(1900, 2, 28), datetime.date(1900, 3, 1)] [datetime.date(1900, 12, 31)]

# 2000 - a leap year
[datetime.date(2000, 2, 28), datetime.date(2000, 2, 29)] [datetime.date(2000, 12, 31)]