我试图用python获取前一个月的日期。
以下是我的尝试:
str( time.strftime('%Y') ) + str( int(time.strftime('%m'))-1 )
然而,这种方式有两个原因:首先,它将返回2012年2月的20122(而不是201202);其次,它将返回0而不是1月的12。
我一下子就解决了这个麻烦
echo $(date -d"3 month ago" "+%G%m%d")
我认为,如果bash有一种内置的方式来实现这一目的,那么python应该提供更好的东西,而不是强迫自己编写脚本来实现这一目标。当然我可以这样做:
if int(time.strftime('%m')) == 1:
return '12'
else:
if int(time.strftime('%m')) < 10:
return '0'+str(time.strftime('%m')-1)
else:
return str(time.strftime('%m') -1)
我还没有测试这段代码,我不想使用它(除非我找不到任何其他方法:/)
谢谢你的帮助!
基于bgporter的回答。
def prev_month_range(when = None):
"""Return (previous month's start date, previous month's end date)."""
if not when:
# Default to today.
when = datetime.datetime.today()
# Find previous month: https://stackoverflow.com/a/9725093/564514
# Find today.
first = datetime.date(day=1, month=when.month, year=when.year)
# Use that to find the first day of this month.
prev_month_end = first - datetime.timedelta(days=1)
prev_month_start = datetime.date(day=1, month= prev_month_end.month, year= prev_month_end.year)
# Return previous month's start and end dates in YY-MM-DD format.
return (prev_month_start.strftime('%Y-%m-%d'), prev_month_end.strftime('%Y-%m-%d'))