在列表中获取当月的日期和日期的差异

时间:2014-03-04 16:40:05

标签: python datetime calendar

我如何打印这些:

  1. 在任何时候,我都应该能够在列表中返回当月的日期。 例如。由于这是三月,我想打印一个列表[20140301, ...,20140331]

  2. 查找当前日期和当月第一天的天数差异。

    e.g。今天是3月4日。我应该能够将差异打印为3 提前致谢

1 个答案:

答案 0 :(得分:0)

以下是您在Python 2.7.3中可以做的事情

from datetime import date 
import calendar
today = date.today()

first_of_month = today.replace(day=1)
_, number_of_days_in_month = calendar.monthrange(first_of_month.year, first_of_month.month)

for i in range(1, number_of_days_in_month+1):
    newdate = today.replace(day = i)
    print newdate #prints all dates in months

#Lets calculate difference between 14th of this month and 1st
randomdate = today.replace(day=14)
delta = randomdate - first_of_month
print delta.days