简体   繁体   English

如何获得给定开始日期和结束日期的中间日期?

[英]How to get the intermediate dates given the start date and end date?

start_date = '07_Nov_2011'
end_date = '10_Jan_2012'

I want to print all the intermediate dates in the same format: 我想以相同格式打印所有中间日期:

day_month_year

If I can somehow convert start_date to date type I can do this: 如果我可以将start_date转换为日期类型,则可以执行以下操作:

sdate+timedelta(1)).strftime('%d_%b_%Y')

How do I convert it? 如何转换? Or is there a better way to do this? 还是有更好的方法来做到这一点?

You can use datetime.datetime.strptime(...) to do the conversion. 您可以使用datetime.datetime.strptime(...)进行转换。 Like this: 像这样:

>>> datetime.datetime.strptime('07_Nov_2011', '%d_%b_%Y').date()
datetime.date(2011, 11, 7)

You can print all the intermediate dates with something like this: 您可以使用以下方式打印所有中间日期:

>>> start_date = '07_Nov_2011'
>>> end_date = '10_Jan_2012'
>>> 
>>> first = datetime.datetime.strptime(start_date, '%d_%b_%Y')
>>> last = datetime.datetime.strptime(end_date, '%d_%b_%Y')
>>> for i in xrange((last-first).days):
...     print (first+datetime.timedelta(i)).strftime('%d_%b_%Y')
... 
07_Nov_2011
08_Nov_2011
09_Nov_2011
10_Nov_2011
11_Nov_2011

etc.

You can parse the dates like so: 您可以像这样解析日期:

import datetime

start_date = '07_Nov_2007'
end_date = '10_Nov_2007'

startDate = datetime.datetime.strptime(start_date, '%d_%b_%Y')
endDate = datetime.datetime.strptime(end_date, '%d_%b_%Y')
oneDay = datetime.timedelta(days = 1)

currentDate = startDate
while currentDate <= endDate:
    print currentDate
    currentDate += oneDay

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python。 如何从日期列表中获取开始和结束日期 - Python. How to get start and end date from list of dates 在python中获取给定月份所有星期的开始和结束日期,不包括其他月份日期 - Get the start and end date of all the weeks for a given month in python exclusive of other months dates 将 2 个给定日期之间的天数拆分为特定的批量大小,并相应地获取 start 和 end_date - Split days between 2 given dates into specific batch size and get the start and end_date accordingly 获取一周的开始日期和结束日期,给定周数和年份 - Get start date and end date of the week, given week number and year 如何找到开始日期和结束日期给出的 dataframe 的差异 - how to find the difference of dataframe which is given on start date and end date 获取开始日期和结束日期 pandas 列之间的所有日期 - Get all dates between start and end date pandas columns 使用 Django 进行日期过滤——如何将开始和结束日期发送到我的视图? - Date filtering with Django -- how to send start and end dates to my view? 如何检查元组之间的日期,日期为开始和结束 - How to check the date in between the tuple, dates as start and end 如何创建具有多个开始和结束日期的日期范围? - How to create date range with multiple start and end dates? 如何在 PySpark 中获取开始和结束日期? - How to get Start and End date in PySpark?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM