Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: get datetime of last hour

People also ask

How do I get hours from datetime?

How to Get the Current Time with the datetime Module. To get the current time in particular, you can use the strftime() method and pass into it the string ”%H:%M:%S” representing hours, minutes, and seconds.

How do you round datetime to hours?

Round time to nearest hour ( TIME(1,0,0) = 1/24 representing an hour) and add a zero time value to ensure the expression is cast as a Time. M: There isn't an equivalent of MROUND in M, so instead multiply the time by 24 to express it as a number of hours, then round, then divide by 24 and convert to a Time type.


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'))

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