简体   繁体   中英

Generate dates for a particular month?

is there any way to generate all the dates of a particular month when the month and year are inputted?

I have

daterange = date_range(date1, date2)
dates=[]
for x in daterange:
    dates.append((x.strftime('%Y-%m-%d')))

using pandas, but how can I account for different month lengths?

您可以使用pd.offsets.MonthBegin ,然后使用每日结束日期范围:

dts = pd.date_range(month_start, month_start + pd.offsets.MonthBegin(1), closed="left") 

You can do that with the calendar module:

import calendar
date_of_first_weekday, number_days_in_month = calendar.monthrange(year, month)

The calendar module has all you need:

import calendar
first_weekday, month_days = calendar.monthrange(year, month)
for mday in xrange(1, month_days + 1):
    print mday

I find I can't import calendar on my system, so here's a datetime -only solution:

from datetime import date, timedelta

month, year = 2, 2008

day = timedelta(days=1)
date1 = date(year, month, 1)
dates = []
d = date1
while d.month == month:
    dates.append(d)
    d += day

(Creates a list of the dates of days in February 2008, a leap year). If you want string representations of the dates, you can use:

from datetime import timedelta, datetime

month, year = 2, 2008

day = timedelta(days=1)
date1 = datetime(year, month, 1)
d = date1
dates = []
while d.month == month:
    dates.append(d.strftime('%Y-%m-%d'))
    d += day

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM