【发布时间】:2012-04-01 06:23:48
【问题描述】:
我正在尝试使用 python 获取上个月的日期。 这是我尝试过的:
str( time.strftime('%Y') ) + str( int(time.strftime('%m'))-1 )
但是,这种方式不好有两个原因:首先它会在 2012 年 2 月返回 20122(而不是 201202),其次它将在 1 月返回 0 而不是 12。
我已经用 bash 解决了这个问题
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)
我没有测试过这段代码,我也不想使用它(除非我找不到其他方法:/)
感谢您的帮助!
【问题讨论】: