python中如何获取每个月的第一天和最后一天(已解决)

python中如何获取每个月的第一天和最后一天(已解决)

 

 

 

import pandas as pd
 
beginDate = '2018-08-01'
endDate = '2019-03-31'
 
 
date_index = pd.date_range(beginDate, endDate)
days = [pd.Timestamp(x).strftime("%Y-%m-%d") for x in date_index.values]
 
tmp = []
for index , v in enumerate(days):
    if index == len(days)-1:
        tmp.append(days[index])
    if index == 0:
        tmp.append(days[0])
    else:
        _ = v.split('-')[2]
        if _ == '01':
            tmp.append(days[index-1])
            tmp.append(days[index])
 
print(tmp)
for i in range(len(tmp)//2):
    print(tmp[i * 2] , tmp[i * 2 + 1])
 
 
 
 
import calendar
import datetime
Format="%d-%d-%d"
year=datetime.datetime.now().year
for i in range(1,13):
   d =calendar.monthrange(year,i)
   print(Format % (year, i, 1))
   print(Format % (year, i, d[1]))
 
 
 
 
 
import datetime
 
for x in xrange(1, 13):
  dt_start = (datetime.datetime(2016, x, 1)).strftime("%Y%m%d")
  if 12 == x:
    dt_end = (datetime.datetime(2016, 12, 31)).strftime("%Y%m%d")
  else:
    dt_end = (datetime.datetime(2016, x+1, 1) - datetime.timedelta(days = 1)).strftime("%Y%m%d")
  print dt_start, dt_end
 
 
 
三种方法,自行取用,注意格式和improt的东西

返回列表
上一篇: