3

Possible Duplicate:
How can I subtract a day from a python date?
subtract two times in python

I had generated date in python as below

import time
time_stamp = time.strftime('%Y-%m-%d')

print time_stamp

Result:

'2012-12-19'

What i am trying is, if above time_stamp is the present today's date , i want a date '2012-12-17' by performing difference(substraction of two days)

So how to perform date reduction of two days from the current date in python

Community
  • 1
  • 1
Shiva Krishna Bavandla
  • 25,548
  • 75
  • 193
  • 313
  • 3
    use the datetime library and datetime objects. datetime.datetime(2012, 12, 17, 00) - datetime.timedelta(days=2) – monkut Dec 21 '12 at 08:01
  • What have you tried? Did you check the datetime API and especially the timedelta API? –  Dec 21 '12 at 08:01
  • Duplicate of http://stackoverflow.com/q/5259882/114147 – invert Dec 21 '12 at 08:25

1 Answers1

1

To perform calculations between some dates in Python use the timedelta class from the datetime module.

To do what you want to achieve, the following code should suffice.

import datetime

time_stamp = datetime.datetime(day=21, month=12, year=2012)

difference = time_stamp - datetime.timedelta(day=2)

print '%s-%s-%s' % (difference.year, difference.year, difference.day)

Explanation of the above:

  • The second line creates a new datetime object (from the the datetime class), with specified day, month and year
  • The third line creates a timedelta object, which is used to perform calculations between datetime objects
NlightNFotis
  • 9,559
  • 5
  • 43
  • 66