我想生成两个日期之间的日期列表,并将它们以字符串格式存储在列表中。这个列表对于与我拥有的其他日期进行比较很有用。
我的代码如下:
from datetime import date, timedelta
sdate = date(2019,3,22) # start date
edate = date(2019,4,9) # end date
def dates_bwn_twodates(start_date, end_date):
for n in range(int ((end_date - start_date).days)):
yield start_date + timedelta(n)
print(dates_bwn_twodates(sdate,edate))
我目前的输出:
<generator object dates_bwn_twodates at 0x000002A8E7929410>
我的预期输出:
['2019-03-22',.....,'2019-04-08']
我的代码有问题。
pandas.date_range()
为此:
import pandas
pandas.date_range(sdate,edate-timedelta(days=1),freq='d')
DatetimeIndex(['2019-03-22', '2019-03-23', '2019-03-24', '2019-03-25',
'2019-03-26', '2019-03-27', '2019-03-28', '2019-03-29',
'2019-03-30', '2019-03-31', '2019-04-01', '2019-04-02',
'2019-04-03', '2019-04-04', '2019-04-05', '2019-04-06',
'2019-04-07', '2019-04-08'],
dtype='datetime64[ns]', freq='D')
您的代码被重写为列表理解:
[sdate+timedelta(days=x) for x in range((edate-sdate).days)]
结果:
[datetime.date(2019, 3, 22),
datetime.date(2019, 3, 23),
datetime.date(2019, 3, 24),
:
datetime.date(2019, 4, 7),
datetime.date(2019, 4, 8)]
我很惊讶这不是日期时间包中的标准函数。
这是一个执行请求的函数:
from datetime import timedelta
def date_range_list(start_date, end_date):
# Return list of datetime.date objects (inclusive) between start_date and end_date (inclusive).
date_list = []
curr_date = start_date
while curr_date <= end_date:
date_list.append(curr_date)
curr_date += timedelta(days=1)
return date_list
用途:
from datetime import date, timedelta
def date_range_list(start_date, end_date):
# Return list of datetime.date objects (inclusive) between start_date and end_date (inclusive).
date_list = []
curr_date = start_date
while curr_date <= end_date:
date_list.append(curr_date)
curr_date += timedelta(days=1)
return date_list
start_date = date(year=2021, month=12, day=20)
stop_date = date(year=2021, month=12, day=25)
date_list = date_range_list(start_date, stop_date)
date_list
输出:
[datetime.date(2021, 12, 20),
datetime.date(2021, 12, 21),
datetime.date(2021, 12, 22),
datetime.date(2021, 12, 23),
datetime.date(2021, 12, 24),
datetime.date(2021, 12, 25)]
虽然上面的代码简单易懂,但为列表提供生成器而不是列表本身会更好。这样,除非需要,否则不需要生成整个日期时间数组并将其存储到内存中。该方法的外观如下:
from datetime import timedelta
def date_range_list(start_date, end_date):
# Return generator for a list datetime.date objects (inclusive) between start_date and end_date (inclusive).
curr_date = start_date
while curr_date <= end_date:
yield curr_date
curr_date += timedelta(days=1)
用途:
from datetime import date, timedelta
def date_range_list(start_date, end_date):
# Return generator for a list datetime.date objects (inclusive) between start_date and end_date (inclusive).
curr_date = start_date
while curr_date <= end_date:
yield curr_date
curr_date += timedelta(days=1)
start_date = date(year=2021, month=12, day=20)
stop_date = date(year=2021, month=12, day=25)
date_list = date_range_list(start_date, stop_date)
for date in date_list:
print(date)
输出:
2021-12-20
2021-12-21
2021-12-22
2021-12-23
2021-12-24
2021-12-25
from datetime import date, timedelta
sdate = date(2019,3,22) # start date
edate = date(2019,4,9) # end date
date_modified=sdate
list=[sdate]
while date_modified<edate:
date_modified+=timedelta(days=nbDaysbtw2dates)
list.append(date_modified)
print(list)
您需要将其显式转换为带有字符串的列表:
print([str(d) for d in dates_bwn_twodates(sdate,edate)])
有一种更简单的方法,只需修改代码即可使用。 如下;
from datetime import datetime, timedelta
from datetime import date
def date_bwn_two_dates(start_date, end_date):
date_list = [] # The list where we want to store
for i in range(int((end_date-start_date).days)+1): # Iterate between the range of dates
year = (start_date+timedelta(i)).strftime("%Y") # Get the Year
month = (start_date+timedelta(i)).strftime("%m") # Get the month
date_a = (start_date+timedelta(i)).strftime("%d") # Get the day
date_list.append([year, month, date_a]) # Append the Objects accquired
return date_list # return the list
for i in date_bwn_two_dates(date(2020, 12, 1), date(2021, 12, 1)):
print(i)
如果您想要日期列表的字符串而不仅仅是日期时间索引,那么还需要使用 strftime
进行格式化from datetime import date, timedelta
def timer():
global datelist
sdate = date(2022, 5, 1)
edate = date(2022, 6, 1)
delta = edate - sdate
datetimes = []
for i in range(delta.days + 1):
day = sdate + timedelta(days=i)
datetimes.append(day)
def formatting():
global converted
converted = pd.to_datetime(datetimes)
return converted
datelist = converted.strftime("%Y-%m-%d").tolist()
formatting()
另一种简单的方法是在 2 个日期时间对象之间使用 numpy np.arange。
from datetime import datetime, timedelta
import numpy as np
start_date = datetime.strptime("2023-06-10", "%Y-%m-%d")
end_date = start_date + timedelta(13)
fut_dates = np.arange(fut_start_date, fut_end_date, dtype="datetime64[D]")
fut_dates:
array(['2023-06-10', '2023-06-11', '2023-06-12', '2023-06-13',
'2023-06-14', '2023-06-15', '2023-06-16', '2023-06-17',
'2023-06-18', '2023-06-19', '2023-06-20', '2023-06-21',
'2023-06-22'], dtype='datetime64[D]')
转换为 datetime.date 对象:
fut_dates.astype(datetime)
array([datetime.date(2023, 6, 10), datetime.date(2023, 6, 11),
datetime.date(2023, 6, 12), datetime.date(2023, 6, 13),
datetime.date(2023, 6, 14), datetime.date(2023, 6, 15),
datetime.date(2023, 6, 16), datetime.date(2023, 6, 17),
datetime.date(2023, 6, 18), datetime.date(2023, 6, 19),
datetime.date(2023, 6, 20), datetime.date(2023, 6, 21),
datetime.date(2023, 6, 22)], dtype=object)
要输出字符串列表,您可以执行类似的操作
[dt.strftime("%Y-%m-%d") for dt in pd.to_datetime(fut_dates)]
返回
['2023-06-10',
'2023-06-11',
'2023-06-12',
'2023-06-13',
'2023-06-14',
'2023-06-15',
'2023-06-16',
'2023-06-17',
'2023-06-18',
'2023-06-19',
'2023-06-20',
'2023-06-21',
'2023-06-22']
您可以使用 https://github.com/zachwill/moment.git 中的 moment 库让您的生活更轻松。
import moment
def dates_bwn_twodates(start_date, end_date):
diff = abs(start_date.diff(end_date).days)
for n in range(0,diff+1):
yield start_date.strftime("%Y-%m-%d")
start_date = (start_date).add(days=1)
sdate = moment.date('2019-03-22') #start date
edate = moment.date('2019-04-09') #end date
然后你就有选择了
dates = list(dates_bwn_twodates(sdate,edate)) #dates as a list
或者你可以迭代
for date in dates_bwn_twodates(sdate,edate):
#do something with each date
这是一个有点老的问题,但我想我应该提出我的建议,因为其中一些似乎使答案过于复杂:
from datetime import date, timedelta
#-- the actual method --#
def get_start_to_end(start_date, end_date):
date_list = []
for i in range(0, (end_date - start_date).days + 1):
date_list.append( str(start_date + timedelta(days=i)) ) #<-- here
return date_list
#-- end of the actual method --#
# -- demonstrating it --#
sd = date(2022,8,12)
ed = date(2022,11,17)
dates = get_start_to_end(sd, ed)
for d in dates:
print(d)
#-- You can just append the date object, the default string (iso)
#-- or use strftime for a different format
#-- (start_date + timedelta(days=i)) <-- date object
#-- str(start_date + timedelta(days=i)) <-- default string
#-- (start_date + timedelta(days=i)).strftime("%b %d, %Y") <-- other string format
也可以使用 本机
dateutil.rrule
模块来完成此操作,这使得它更短且易于阅读。
这是一个例子:
# With relativedelta
import datetime
from dateutil.relativedelta import relativedelta
dates = []
end = datetime.datetime(2024,10,4)
start = datetime.datetime(2024,10,1)
for days in range((end-start).days):
date = start + relativedelta(days=days)
dates.append(date.strftime("%Y-%m-%d"))
# with rrule
import datetime
from dateutil.rrule import rrule, DAILY
end = datetime.datetime(2024,10,4)
start = datetime.datetime(2024,10,1)
days = (end-start).days
dates = [day.strftime("%Y-%m-%d") for day in rrule(freq=DAILY, dtstart=start, count=days)]
输出:
['2024-10-01', '2024-10-02', '2024-10-03']