Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python date of the previous month

Tags:

python

date

time

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 )

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.

I have solved this trouble in bash with

echo $(date -d"3 month ago" "+%G%m%d")

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:/)

Thanks for your help!

like image 260
philippe Avatar asked Oct 20 '22 11:10

philippe


People also ask

How do I get the first and last date of a previous month in Python?

Method #1 : Using replace() + timedelta() In this, extract the next month, and subtract the day of next month object extracted from the next month, resulting in 1 day before beginning of next month, i.e last date of current month.


1 Answers

datetime and the datetime.timedelta classes are your friend.

  1. find today.
  2. use that to find the first day of this month.
  3. use timedelta to backup a single day, to the last day of the previous month.
  4. print the YYYYMM string you're looking for.

Like this:

 import datetime
 today = datetime.date.today()
 first = today.replace(day=1)
 last_month = first - datetime.timedelta(days=1)
 print(last_month.strftime("%Y%m"))
 

201202 is printed.

like image 437
bgporter Avatar answered Oct 21 '22 23:10

bgporter