24

To get now, I can do:

now = datetime.datetime.now()

How would I get 24 hours ago?

now - 24 hrs. ?
David542
  • 101,766
  • 154
  • 423
  • 727

2 Answers2

56

Use timedelta:

datetime.datetime.now() - datetime.timedelta(days=1)

http://docs.python.org/2/library/datetime.html#timedelta-objects

David542
  • 101,766
  • 154
  • 423
  • 727
11

you could use:

datetime.date.fromordinal(datetime.date.today().toordinal()-1)

Get yesterday's date in Python, DST-safe

this will help with formatting:

http://www.cyberciti.biz/faq/howto-get-current-date-time-in-python/

Community
  • 1
  • 1
Plasmarob
  • 1,271
  • 12
  • 20