64

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?

Rishav Sharan
  • 2,763
  • 8
  • 39
  • 55

3 Answers3

124

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'))
sjas
  • 18,644
  • 14
  • 87
  • 92
Adam Morris
  • 8,265
  • 12
  • 45
  • 68
  • This is the way I always do it, but I wish I had a 1 function way to write this instead of calling 2 functions and subtracting. I might make a simple library for it. – Gattster Nov 24 '14 at 04:40
  • 1
    Careful: This appears to return unexpected results. `datetime.now()` is [definitely preferred](http://stackoverflow.com/questions/32298332/python3-4-datetime-today-and-datetime-now). – James Taylor Mar 12 '17 at 01:44
  • Warning, you are using `datetime.now()` but datetime is not imported, I edited the answer. – Gugu72 Apr 10 '20 at 09:00
22

This works for me:

import datetime

lastHourDateTime = datetime.datetime.now() - datetime.timedelta(hours = 1)
print(lastHourDateTime.strftime('%Y-%m-%d %H'))

# prints "2011-09-28 12" which is the time one hour ago in Central Europe
sjas
  • 18,644
  • 14
  • 87
  • 92
eumiro
  • 207,213
  • 34
  • 299
  • 261
2

You can achieve the same goal using pandas:

import pandas as pd
pd.Timestamp.now() - pd.Timedelta('1 hours')
nimbous
  • 1,507
  • 9
  • 12