在Python中创建日期范围

我想创建一个日期列表,从今天开始,追溯到任意天数,例如,在我的示例中是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
787642 次浏览

稍微更好……

base = datetime.datetime.today()
date_list = [base - datetime.timedelta(days=x) for x in range(numdays)]

你可以写一个生成器函数,返回从今天开始的日期对象:

import datetime


def date_generator():
from_date = datetime.datetime.today()
while True:
yield from_date
from_date = from_date - datetime.timedelta(days=1)

这个生成器返回从今天开始的日期,一次返回一天。以下是前3次约会的方法:

>>> 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)]

我知道这个回答有点晚,但我也遇到了同样的问题,我认为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))

以下是我从自己的代码中创建的要点,这可能会有所帮助。(我知道这个问题太老了,但其他人可以用)

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

是的,重新发明轮子.... 只要搜索论坛,你会得到这样的东西:

from dateutil import rrule
from datetime import datetime


list(rrule.rrule(rrule.DAILY,count=100,dtstart=datetime.now()))

Pandas对于一般的时间序列来说很好,并且直接支持日期范围。

例如pd.date_range():

import pandas as pd
from datetime import datetime


datelist = pd.date_range(datetime.today(), periods=100).tolist()

它也有很多选择,让生活更轻松。例如,如果您只想要工作日,您只需交换bdate_range

看到# EYZ0

此外,它完全支持pytz时区,可以平滑地跨越春季/秋季夏令时转换。

编辑由OP:

如果你需要实际的python日期时间,而不是Pandas时间戳:

import pandas as pd
from datetime import datetime


pd.date_range(end = datetime.today(), periods = 100).to_pydatetime().tolist()


#OR


pd.date_range(start="2018-09-09",end="2020-02-02")


这使用"end"参数来匹配原始问题,但如果你想要降序日期:

pd.date_range(datetime.today(), periods=100).to_pydatetime().tolist()

获取指定的开始日期和结束日期之间的日期范围(为时间和amp优化;空间复杂度):

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")

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)
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()

你也可以使用日期序数来简化:

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(),
)
]

下面是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
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

从这个问题的标题中,我希望找到像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))]

所有功劳都归这个答案!

下面是一个稍微不同的答案,建立在S.Lott的答案之上,给出了两个日期startend之间的日期列表。在下面的例子中,从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)]

根据我自己的回答:

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”对象,而不是“datetime.datetime”对象。

如果有两个日期,你需要范围试试

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)))

我知道这个问题已经有人回答了,但为了历史的目的,我还是把我的答案写下来,因为我认为这是直截了当的。

import numpy as np
import datetime as dt
listOfDates=[date for date in np.arange(firstDate,lastDate,dt.timedelta(days=x))]

当然,它不会像代码高尔夫那样赢得任何东西,但我认为它很优雅。

一个月日期范围生成器,使用datetimedateutil。简单易懂的:

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)

从上面的答案,我创建了这个例子的日期生成器

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)

另一个向前或向后计数的例子,从桑迪普的回答开始。

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)

我想用一个简单(不完整)的日期范围实现来发表我的意见:

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))
)

一个泛型方法,允许在参数化窗口大小(天,分钟,小时,秒)上创建日期范围:

from datetime import datetime, timedelta


def create_date_ranges(start, end, **interval):
start_ = start
while start_ < end:
end_ = start_ + timedelta(**interval)
yield (start_, min(end_, end))
start_ = end_

测试:

def main():
tests = [
('2021-11-15:00:00:00', '2021-11-17:13:00:00', {'days': 1}),
('2021-11-15:00:00:00', '2021-11-16:13:00:00', {'hours': 12}),
('2021-11-15:00:00:00', '2021-11-15:01:45:00', {'minutes': 30}),
('2021-11-15:00:00:00', '2021-11-15:00:01:12', {'seconds': 30})
]
for t in tests:
print("\nInterval: %s, range(%s to %s)" % (t[2], t[0], t[1]))
start = datetime.strptime(t[0], '%Y-%m-%d:%H:%M:%S')
end =  datetime.strptime(t[1], '%Y-%m-%d:%H:%M:%S')
ranges = list(create_date_ranges(start, end, **t[2]))
x = list(map(
lambda x: (x[0].strftime('%Y-%m-%d:%H:%M:%S'), x[1].strftime('%Y-%m-%d:%H:%M:%S')),
ranges
))
print(x)
main()

测试输出:

Interval: {'days': 1}, range(2021-11-15:00:00:00 to 2021-11-17:13:00:00)
[('2021-11-15:00:00:00', '2021-11-16:00:00:00'), ('2021-11-16:00:00:00', '2021-11-17:00:00:00'), ('2021-11-17:00:00:00', '2021-11-17:13:00:00')]


Interval: {'hours': 12}, range(2021-11-15:00:00:00 to 2021-11-16:13:00:00)
[('2021-11-15:00:00:00', '2021-11-15:12:00:00'), ('2021-11-15:12:00:00', '2021-11-16:00:00:00'), ('2021-11-16:00:00:00', '2021-11-16:12:00:00'), ('2021-11-16:12:00:00', '2021-11-16:13:00:00')]


Interval: {'minutes': 30}, range(2021-11-15:00:00:00 to 2021-11-15:01:45:00)
[('2021-11-15:00:00:00', '2021-11-15:00:30:00'), ('2021-11-15:00:30:00', '2021-11-15:01:00:00'), ('2021-11-15:01:00:00', '2021-11-15:01:30:00'), ('2021-11-15:01:30:00', '2021-11-15:01:45:00')]


Interval: {'seconds': 30}, range(2021-11-15:00:00:00 to 2021-11-15:00:01:12)
[('2021-11-15:00:00:00', '2021-11-15:00:00:30'), ('2021-11-15:00:00:30', '2021-11-15:00:01:00'), ('2021-11-15:00:01:00', '2021-11-15:00:01:12')]
from datetime import datetime , timedelta, timezone




start_date = '2022_01_25'
end_date = '2022_01_30'


start = datetime.strptime(start_date, "%Y_%m_%d")
print(type(start))
end =  datetime.strptime(end_date, "%Y_%m_%d")
##pDate = str(pDate).replace('-', '_')
number_of_days = (end - start).days


print("number_of_days: ", number_of_days)


##
date_list = []
for day in range(number_of_days):
a_date = (start + timedelta(days = day)).astimezone(timezone.utc)
a_date = a_date.strftime('%Y-%m-%d')
date_list.append(a_date)


print(date_list)