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 )
<
datetime and the datetime.timedelta classes are your friend.
Like this:
import datetime
today = datetime.date.today()
first = today.replace(day=1)
lastMonth = first - datetime.timedelta(days=1)
print(lastMonth.strftime("%Y%m"))
201202
is printed.
You should use dateutil. With that, you can use relativedelta, it's an improved version of timedelta.
>>> import datetime
>>> import dateutil.relativedelta
>>> now = datetime.datetime.now()
>>> print now
2012-03-15 12:33:04.281248
>>> print now + dateutil.relativedelta.relativedelta(months=-1)
2012-02-15 12:33:04.281248
def prev_month(date=datetime.datetime.today()):
if date.month == 1:
return date.replace(month=12,year=date.year-1)
else:
try:
return date.replace(month=date.month-1)
except ValueError:
return prev_month(date=date.replace(day=date.day-1))
Just for fun, a pure math answer using divmod. Pretty inneficient because of the multiplication, could do just as well a simple check on the number of month (if equal to 12, increase year, etc)
year = today.year
month = today.month
nm = list(divmod(year * 12 + month + 1, 12))
if nm[1] == 0:
nm[1] = 12
nm[0] -= 1
pm = list(divmod(year * 12 + month - 1, 12))
if pm[1] == 0:
pm[1] = 12
pm[0] -= 1
next_month = nm
previous_month = pm
If you want to look at the ASCII letters in a EXE type file in a LINUX/UNIX Environment, try "od -c 'filename' |more"
You will likely get a lot of unrecognizable items, but they will all be presented, and the HEX representations will be displayed, and the ASCII equivalent characters (if appropriate) will follow the line of hex codes. Try it on a compiled piece of code that you know. You might see things in it you recognize.
There is a high level library dateparser that can determine the past date given natural language, and return the corresponding Python datetime
object
from dateparser import parse
parse('4 months ago')