Python: get datetime of last hour

Rishav Sharan picture Rishav Sharan · Sep 28, 2011 · Viewed 59.4k times · Source

I want to get the date time object for last hour. Lets say the sys time is "2011-9-28 06:11:30" I want to get the output as "2011-9-28 05" #{06 - 1 hour}

I used:

    lastHourDateTime = date.today() - timedelta(hours = 1)
    print lastHourDateTime.strftime('%Y-%m-%d %H:%M:%S')

However, my output is not showing the time part at all. where am I going wrong?

Answer

Adam Morris picture Adam Morris · Sep 28, 2011

Date doesn't have the hour - use datetime:

from datetime import datetime, timedelta
last_hour_date_time = datetime.now() - timedelta(hours = 1)
print last_hour_date_time.strftime('%Y-%m-%d %H:%M:%S')