在Python中获取给定字符串的日期列表

时间:2019-03-22 12:32:03

标签: python pandas datetime

我在python中有一个字符串,

date="200601"

代表2006 January

如何获取“ yyyy-mm-dd”格式的特定月份的日期列表

,以及如何将200601迭代到201903,即。获取两个月之间的所有值。

example 200601,200602,200603...

非常感谢!

1 个答案:

答案 0 :(得分:1)

dates的格式获取month的{​​{1}}中的所有year

yyyy-mm-dd

输出

date = "200601"

import datetime, calendar
num_days = calendar.monthrange(int(date[:-2]), int(date[4:]))[1]
print([datetime.date(int(date[:-2]), int(date[4:]), day).strftime("%Y-%m-%d") for day in range(1, num_days+1)])

第二个问题:

Print all day-dates between two dates

编辑

从此答案下的评论继续:

['2006-01-01', '2006-01-02', '2006-01-03', '2006-01-04', '2006-01-05', '2006-01-06', '2006-01-07', '2006-01-08', '2006-01-09', '2006-01-10', '2006-01-11', '2006-01-12', '2006-01-13', '2006-01-14', '2006-01-15', '2006-01-16', '2006-01-17', '2006-01-18', '2006-01-19', '2006-01-20', '2006-01-21', '2006-01-22', '2006-01-23', '2006-01-24', '2006-01-25', '2006-01-26', '2006-01-27', '2006-01-28', '2006-01-29', '2006-01-30', '2006-01-31']

输出

print([datetime.date(int(date[:-2]), int(date[4:]), day).strftime("%Y%d") for day in range(1, num_days+1)])