=Start=
缘由:
突然想到的一个问题,觉得比较有趣,就实际测试了一下,考虑到以后可能会有用,就记录一下。
正文:
搜索关键字:
python get every first day of month
参考解答:
方法一:
>>> import calendar >>> calendar.monthrange(2002,1) (1, 31) >>> calendar.monthrange(2008,2) (4, 29) >>> calendar.monthrange(2100,2) (0, 28) >>> calendar.monthrange(2016, 2)[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
参考链接:
- http://stackoverflow.com/questions/42950/get-last-day-of-the-month-in-python
- https://docs.python.org/2/library/calendar.html
- https://docs.python.org/2/library/datetime.html
- http://stackoverflow.com/questions/22696662/python-list-of-first-day-of-month-for-given-period
=END=
《 “在Python中如何获取某年中每个月的第一天和最后一天?” 》 有 2 条评论
PYTHON-基础-时间日期处理小结
http://www.wklken.me/posts/2015/03/03/python-base-datetime.html
https://pymotw.com/2/datetime/
python 时间模块小结(time and datetime)
http://peiqiang.net/2014/08/15/python-time-and-datetime.html
Python中如何「单行」快速获取昨天的日期字符串(YYYY-mm-dd格式)
http://stackoverflow.com/questions/30483977/python-get-yesterdays-date-as-a-string-in-yyyy-mm-dd-format
`
>>> import datetime
>>> datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime(“%F”)
‘2016-12-12’
`
Python中如何获取当前日期所在星期的星期一
https://stackoverflow.com/questions/19216334/python-give-start-and-end-of-week-data-from-a-given-date
`
import datetime
dt_today = datetime.datetime.now()
week_start = dt_today – datetime.timedelta(days=dt_today.weekday())
week_end = week_start + datetime.timedelta(days=6)
print ‘当天日期: {0},\n星期几: {1},\n一周中的第几天(从0算起): {2},\n一周中的第几天(从1算起): {3}\n’.format(dt_today.strftime(“%F”), dt_today.strftime(“%A”), dt_today.weekday(), dt_today.isoweekday())
print ‘本周的星期一的日期: {0},\n本周的星期天的日期: {1}’.format(week_start.strftime(“%F”), week_end.strftime(“%F”))
”’
当天日期: 2018-12-14,
星期几: Friday,
一周中的第几天(从0算起): 4,
一周中的第几天(从1算起): 5
本周的星期一的日期: 2018-12-10,
本周的星期天的日期: 2018-12-16
”’
`