我想创建一个日期列表,从今天开始,然后返回任意天数,例如,在我的示例中为100天。有没有比这更好的方法呢?
import datetime
a = datetime.datetime.today()
numdays = 100
dateList = []
for x in range (0, numdays):
dateList.append(a - datetime.timedelta(days = x))
print dateList
答案 0 :(得分:374)
边缘更好......
base = datetime.datetime.today()
date_list = [base - datetime.timedelta(days=x) for x in range(0, numdays)]
答案 1 :(得分:181)
Pandas
一般适用于时间序列,并且直接支持日期范围。
import pandas as pd
datelist = pd.date_range(pd.datetime.today(), periods=100).tolist()
它还有很多选项可以让生活更轻松。例如,如果您只想要工作日,则只需交换bdate_range
。
请参阅http://pandas.pydata.org/pandas-docs/stable/timeseries.html#generating-ranges-of-timestamps
此外,它完全支持pytz时区,可以顺利跨越春秋季DST班次。
答案 2 :(得分:52)
获取指定开始日期和结束日期之间的日期范围(针对时间和空间复杂度进行了优化):
import datetime
start = datetime.datetime.strptime("21-06-2014", "%d-%m-%Y")
end = datetime.datetime.strptime("07-07-2014", "%d-%m-%Y")
date_generated = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)]
for date in date_generated:
print date.strftime("%d-%m-%Y")
答案 3 :(得分:40)
您可以编写一个从今天开始返回日期对象的生成器函数:
import datetime
def date_generator():
from_date = datetime.datetime.today()
while True:
yield from_date
from_date = from_date - datetime.timedelta(days=1)
此生成器从今天开始返回日期,一次向后返回一天。以下是前三个日期:
>>> import itertools
>>> dates = itertools.islice(date_generator(), 3)
>>> list(dates)
[datetime.datetime(2009, 6, 14, 19, 12, 21, 703890), datetime.datetime(2009, 6, 13, 19, 12, 21, 703890), datetime.datetime(2009, 6, 12, 19, 12, 21, 703890)]
这种方法优于循环或列表理解的优势在于您可以根据需要返回多次。
修改强>
使用生成器表达式而不是函数的更紧凑版本:
date_generator = (datetime.datetime.today() - datetime.timedelta(days=i) for i in itertools.count())
用法:
>>> dates = itertools.islice(date_generator, 3)
>>> list(dates)
[datetime.datetime(2009, 6, 15, 1, 32, 37, 286765), datetime.datetime(2009, 6, 14, 1, 32, 37, 286836), datetime.datetime(2009, 6, 13, 1, 32, 37, 286859)]
答案 4 :(得分:31)
你也可以使用day ordinal来简化:
def date_range(start_date, end_date):
for ordinal in range(start_date.toordinal(), end_date.toordinal()):
yield datetime.date.fromordinal(ordinal)
或者按照评论中的建议,您可以创建如下列表:
date_range = [
datetime.date.fromordinal(ordinal)
for ordinal in range(
start_date.toordinal(),
end_date.toordinal(),
)
]
答案 5 :(得分:28)
from dateutil import rrule
from datetime import datetime
list(rrule.rrule(rrule.DAILY,count=100,dtstart=datetime.now()))
答案 6 :(得分:15)
从这个问题的标题我希望找到类似range()
的内容,这将让我指定两个日期并创建一个列表,其中包含所有日期。这样,如果事先不知道,那么就不需要计算这两个日期之间的天数。
因此,如果有一点点偏离主题的风险,这个单行就能胜任:
import datetime
start_date = datetime.date(2011, 01, 01)
end_date = datetime.date(2014, 01, 01)
dates_2011_2013 = [ start_date + datetime.timedelta(n) for n in range(int ((end_date - start_date).days))]
this answer的所有积分!
答案 7 :(得分:7)
我知道一些迟到的答案,但我遇到了同样的问题,并且认为Python的内部范围函数在这方面有点缺乏,所以我在我的util模块中重写了它。
from __builtin__ import range as _range
from datetime import datetime, timedelta
def range(*args):
if len(args) != 3:
return _range(*args)
start, stop, step = args
if start < stop:
cmp = lambda a, b: a < b
inc = lambda a: a + step
else:
cmp = lambda a, b: a > b
inc = lambda a: a - step
output = [start]
while cmp(start, stop):
start = inc(start)
output.append(start)
return output
print range(datetime(2011, 5, 1), datetime(2011, 10, 1), timedelta(days=30))
答案 8 :(得分:7)
这里的答案略有不同,以S.Lott的答案为基础,给出了两个日期start
和end
之间的日期列表。在下面的例子中,从2017年初到今天。
start = datetime.datetime(2017,1,1)
end = datetime.datetime.today()
daterange = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)]
答案 9 :(得分:5)
这是我创建的要点,从我自己的代码中,这可能会有所帮助。 (我知道问题太旧了,但其他人可以使用它)
https://gist.github.com/2287345
(下同)
import datetime
from time import mktime
def convert_date_to_datetime(date_object):
date_tuple = date_object.timetuple()
date_timestamp = mktime(date_tuple)
return datetime.datetime.fromtimestamp(date_timestamp)
def date_range(how_many=7):
for x in range(0, how_many):
some_date = datetime.datetime.today() - datetime.timedelta(days=x)
some_datetime = convert_date_to_datetime(some_date.date())
yield some_datetime
def pick_two_dates(how_many=7):
a = b = convert_date_to_datetime(datetime.datetime.now().date())
for each_date in date_range(how_many):
b = a
a = each_date
if a == b:
continue
yield b, a
答案 10 :(得分:4)
这里有一个用于bash脚本的单行程序来获取工作日列表,这是python 3.无论如何都很容易修改,最后的int是你想要的天数。
python -c "import sys,datetime; print('\n'.join([(datetime.datetime.today() - datetime.timedelta(days=x)).strftime(\"%Y/%m/%d\") for x in range(0,int(sys.argv[1])) if (datetime.datetime.today() - datetime.timedelta(days=x)).isoweekday()<6]))" 10
这是提供开始(或更确切地说,结束)日期的变体
python -c "import sys,datetime; print('\n'.join([(datetime.datetime.strptime(sys.argv[1],\"%Y/%m/%d\") - datetime.timedelta(days=x)).strftime(\"%Y/%m/%d \") for x in range(0,int(sys.argv[2])) if (datetime.datetime.today() - datetime.timedelta(days=x)).isoweekday()<6]))" 2015/12/30 10
以下是任意开始日期和结束日期的变体。并不是说这不是非常有效,但是有利于在bash脚本中加入for循环:
python -c "import sys,datetime; print('\n'.join([(datetime.datetime.strptime(sys.argv[1],\"%Y/%m/%d\") + datetime.timedelta(days=x)).strftime(\"%Y/%m/%d\") for x in range(0,int((datetime.datetime.strptime(sys.argv[2], \"%Y/%m/%d\") - datetime.datetime.strptime(sys.argv[1], \"%Y/%m/%d\")).days)) if (datetime.datetime.strptime(sys.argv[1], \"%Y/%m/%d\") + datetime.timedelta(days=x)).isoweekday()<6]))" 2015/12/15 2015/12/30
答案 11 :(得分:4)
如果有两个日期并且你需要范围试试
from dateutil import rrule, parser
date1 = '1995-01-01'
date2 = '1995-02-28'
datesx = list(rrule.rrule(rrule.DAILY, dtstart=parser.parse(date1), until=parser.parse(date2)))
答案 12 :(得分:3)
基于我为自己写的答案:
import datetime;
print [(datetime.date.today() - datetime.timedelta(days=x)).strftime('%Y-%m-%d') for x in range(-5, 0)]
输出:
['2017-12-11', '2017-12-10', '2017-12-09', '2017-12-08', '2017-12-07']
不同之处在于我得到了date
&#39;对象,而不是&{39; datetime.datetime
&#39;之一。
答案 13 :(得分:3)
Matplotlib相关
from matplotlib.dates import drange
import datetime
base = datetime.date.today()
end = base + datetime.timedelta(days=100)
delta = datetime.timedelta(days=1)
l = drange(base, end, delta)
答案 14 :(得分:2)
我知道这已经得到了解答,但我会为了历史目的而放下我的答案,因为我认为这是直截了当的。
import numpy as np
import datetime as dt
listOfDates=[date for date in np.arange(firstDate,lastDate,dt.timedelta(days=x))]
当然,它不会像代码高尔夫那样获胜,但我认为它很优雅。
答案 15 :(得分:1)
from datetime import datetime, timedelta
from dateutil import parser
def getDateRange(begin, end):
""" """
beginDate = parser.parse(begin)
endDate = parser.parse(end)
delta = endDate-beginDate
numdays = delta.days + 1
dayList = [datetime.strftime(beginDate + timedelta(days=x), '%Y%m%d') for x in range(0, numdays)]
return dayList
答案 16 :(得分:1)
具有datetime
和dateutil
的每月日期范围生成器。简单易懂:
import datetime as dt
from dateutil.relativedelta import relativedelta
def month_range(start_date, n_months):
for m in range(n_months):
yield start_date + relativedelta(months=+m)
答案 17 :(得分:0)
import datetime
def date_generator():
cur = base = datetime.date.today()
end = base + datetime.timedelta(days=100)
delta = datetime.timedelta(days=1)
while(end>base):
base = base+delta
print base
date_generator()
答案 18 :(得分:0)
从以上答案中,我为日期生成器创建了此示例
import datetime
date = datetime.datetime.now()
time = date.time()
def date_generator(date, delta):
counter =0
date = date - datetime.timedelta(days=delta)
while counter <= delta:
yield date
date = date + datetime.timedelta(days=1)
counter +=1
for date in date_generator(date, 30):
if date.date() != datetime.datetime.now().date():
start_date = datetime.datetime.combine(date, datetime.time())
end_date = datetime.datetime.combine(date, datetime.time.max)
else:
start_date = datetime.datetime.combine(date, datetime.time())
end_date = datetime.datetime.combine(date, time)
print('start_date---->',start_date,'end_date---->',end_date)
答案 19 :(得分:0)
从Sandeep的答案开始,另一个向前或向后计数的示例。
from datetime import date, datetime, timedelta
from typing import Sequence
def range_of_dates(start_of_range: date, end_of_range: date) -> Sequence[date]:
if start_of_range <= end_of_range:
return [
start_of_range + timedelta(days=x)
for x in range(0, (end_of_range - start_of_range).days + 1)
]
return [
start_of_range - timedelta(days=x)
for x in range(0, (start_of_range - end_of_range).days + 1)
]
start_of_range = datetime.today().date()
end_of_range = start_of_range + timedelta(days=3)
date_range = range_of_dates(start_of_range, end_of_range)
print(date_range)
给予
[datetime.date(2019, 12, 20), datetime.date(2019, 12, 21), datetime.date(2019, 12, 22), datetime.date(2019, 12, 23)]
和
start_of_range = datetime.today().date()
end_of_range = start_of_range - timedelta(days=3)
date_range = range_of_dates(start_of_range, end_of_range)
print(date_range)
给予
[datetime.date(2019, 12, 20), datetime.date(2019, 12, 19), datetime.date(2019, 12, 18), datetime.date(2019, 12, 17)]
请注意,开始日期包含在退货中,因此,如果您要总共四个日期,请使用timedelta(days=3)
答案 20 :(得分:0)
我想我会简单地(而不是完整地)实现日期范围,花掉我两分钱:
from datetime import date, timedelta, datetime
class DateRange:
def __init__(self, start, end, step=timedelta(1)):
self.start = start
self.end = end
self.step = step
def __iter__(self):
start = self.start
step = self.step
end = self.end
n = int((end - start) / step)
d = start
for _ in range(n):
yield d
d += step
def __contains__(self, value):
return (
(self.start <= value < self.end) and
((value - self.start) % self.step == timedelta(0))
)