26

To get now, I can do:

now = datetime.datetime.now()

How would I get 24 hours ago?

now - 24 hrs. ?
David542
  • 104,438
  • 178
  • 489
  • 842

2 Answers2

58

Use timedelta:

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

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

David542
  • 104,438
  • 178
  • 489
  • 842
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,321
  • 12
  • 20