上个月的python日期 [英] python date of the previous month
问题描述
我试图用python来获取上个月的日期。
这是我试过的:
I am trying to get the date of the previous month with python. Here is what i've tried:
str( time.strftime('%Y') ) + str( int(time.strftime('%m'))-1 )
然而,这样做有两个原因:首先它返回20122年2012年2月(而不是201202),其次它将返回0而不是12月1月。
However, this way is bad for 2 reasons: First it returns 20122 for the February of 2012 (instead of 201202) and secondly it will return 0 instead of 12 on January.
我已经解决了echo $(date -d3个月前+%G%m%d)
I have solved this trouble in bash with
echo $(date -d"3 month ago" "+%G%m%d")
我认为,如果bash有一个内置的方式为此目的,那么python,应该提供比强制编写自己的脚本来实现这个目标更好的东西。当然我可以这样做:
I think that if bash has a built-in way for this purpose, then python, much more equipped, should provide something better than forcing writing one's own script to achieve this goal. Of course i could do something like:
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)
我没有测试这段代码,我不想使用它(除非我可以'感谢您的帮助!
I have not tested this code and i don't want to use it anyway (unless I can't find any other way:/)
推荐答案
可以找到任何其他方式:/ /
datetime ,datetime.timedelta类是您的朋友。
datetime and the datetime.timedelta classes are your friend.
- 今天查询
- 使用它来查找本月的第一天。
- 打印您要查找的YYYYMM字符串。
- find today.
- use that to find the first day of this month.
- use timedelta to backup a single day, to the last day of the previous month.
- print the YYYYMM string you're looking for.
像这样:
>>> import datetime
>>> today = datetime.date.today()
>>> first = today.replace(day=1)
>>> lastMonth = first - datetime.timedelta(days=1)
>>> print lastMonth.strftime("%Y%m")
201202
>>>
这篇关于上个月的python日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!