Python获取当天日期,昨天日期,明天日期,本周第一天日期,上周第一天日期,本月第一天日期,上月第一天日期,本季度第一天日期,上季度第一天日期,本年第一天日期,上年第一天日期的方法
import calendar
import datetime
now = datetime.datetime.now()
print(now)
now = datetime.datetime.now().date()
print(now)
now = datetime.date.today()
print(now)
yesterday = now - datetime.timedelta(days=1)
print(yesterday)
tomorrow = now + datetime.timedelta(days=1)
print(tomorrow)
this_week_start = now - datetime.timedelta(days=now.weekday())
this_week_end = now + datetime.timedelta(days=6-now.weekday())
print(now.weekday())
print('本周第一天:' + this_week_start.strftime('%Y%m%d') + ' 本周最后一天:' + this_week_end.strftime('%Y%m%d') )
last_week_start = now - datetime.timedelta(days=now.weekday()+7)
last_week_end = now - datetime.timedelta(days=now.weekday()+1)
print('上周第一天:' + last_week_start.strftime('%Y%m%d') + ' 上周最后一天:' + last_week_end.strftime('%Y%m%d') )
this_month_start = datetime.datetime(now.year, now.month, 1)
this_month_end = datetime.datetime(now.year, now.month, calendar.monthrange(now.year, now.month)[1])
print('本月第一天:' + this_month_start.strftime('%Y%m%d') + ' 本月最后一天:' + this_month_end.strftime('%Y%m%d') )
last_month_end = this_month_start - datetime.timedelta(days=1)
last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1)
print('上月第一天:' + last_month_start.strftime('%Y%m%d') + ' 上月最后一天:' + last_month_end.strftime('%Y%m%d') )
month = now.month - (now.month - 1) % 3
this_quarter_start = datetime.datetime(now.year, month, 1)
this_quarter_end = datetime.datetime(now.year, month + 2, calendar.monthrange(now.year, month + 2)[1])
print('本季第一天:' + this_quarter_start.strftime('%Y%m%d') + ' 本季最后一天:' + this_quarter_end.strftime('%Y%m%d') )
last_quarter_end = this_quarter_start - datetime.timedelta(days=1)
last_quarter_start = datetime.datetime(last_quarter_end.year, last_quarter_end.month - 2, 1)
print('上季第一天:' + last_quarter_start.strftime('%Y%m%d') + ' 上季最后一天:' + last_quarter_end.strftime('%Y%m%d') )
this_year_start = datetime.datetime(now.year, 1, 1)
this_year_end = datetime.datetime(now.year + 1, 1, 1) - datetime.timedelta(days=1)
print('本年第一天:' + this_year_start.strftime('%Y%m%d') + ' 本年最后一天:' + this_year_end.strftime('%Y%m%d') )
last_year_end = this_year_start - datetime.timedelta(days=1)
last_year_start = datetime.datetime(last_year_end.year, 1, 1)
print('上年第一天:' + last_year_start.strftime('%Y%m%d') + ' 上年最后一天:' + last_year_end.strftime('%Y%m%d') )