Python: get datetime of last hour

PythonDatetimeHour

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

Solution 3 - Python

You can achieve the same goal using pandas:

import pandas as pd
pd.Timestamp.now() - pd.Timedelta('1 hours')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRishav SharanView Question on Stackoverflow
Solution 1 - PythonAdam MorrisView Answer on Stackoverflow
Solution 2 - PythoneumiroView Answer on Stackoverflow
Solution 3 - PythonnimbousView Answer on Stackoverflow