1

I have to get the date of the day approximately one month before from today in python. The resulting string should be of the format yyyy/mm/dd

The date has to be approximate, so things like considering the leap year and all can be avoided (or if easy can be incorporated as well)

I have written the following code for the above problem

from datetime import date
tup=list(date.today().timetuple()[0:3])
if (tup[1]==1):
    tup[1]=12
    tup[0]-=1
else:
   tup[1]-=1
   if tup[1]==2:
      tup[2]=min(28,tup[2])
   else if tup[1] in [4,6,9,11]:
      tup[2]=min(30,tup[2])
print '/'.join([str(x) for x in tup])

Is there a more elegant way to solve the above problem??

4 Answers 4

3

You can use the datetime class in conjunction with the timedelta function.

i.e.

>>> from datetime import date, timedelta
>>> days=30
>>> d = date.today() - timedelta(days=days)
>>> print d
2014-06-29

Then, to format:

from datetime import datetime
dt = datetime.strftime(d, "%Y/%m/%d")
>>> print dt
2014/06/29
Sign up to request clarification or add additional context in comments.

Comments

2

Just an alternative solution using a third-party package called Delorean:

>>> from delorean import Delorean
>>> d = Delorean()
>>> d.last_month().date.strftime('%Y/%m/%d')
'2014/06/29'

1 Comment

Will using a third-party package on a server be an additional overhead?
0

You can use DateUtil's relativedelta function for this functionality as well. It handles days in a month and leap years appropriately, like alecxe's library does.

If you don't have the DateUtil library, first install that

pip install python-dateutil

Then you can utilize it like this:

>>> import datetime
>>> from dateutil.relativedelta import relativedelta
>>> now = datetime.datetime.today()
>>> now + relativedelta(months=1)
datetime.datetime(2014, 8, 29, 0, 32, 51, 843000)
>>> now + relativedelta(months=-1)
datetime.datetime(2014, 6, 29, 0, 32, 51, 843000)

Finally, to format it, you need to use the strftime function.

>>> (now + relativedelta(months=-1)).strftime('%Y/%m/%d')
'2014/06/29'

Comments

0

datetime is the correct module here..

import datetime
datetime.datetime.now().strftime("%H:%M:%S.%f")

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.