简体   繁体   中英

get gmt time two hours ago Python 2.7

Hi I am having trouble getting the time two hours ago in a similar function to my get_timestamp =>

def get_timestamp():
    """Return correctly formatted timestamp"""
    return strftime("%Y-%m-%dT%H:%M:%SZ", gmtime())
def two_hours_ago():
    """Return correctly formatted timestamp"""
    last = (date.today() - timedelta(hours=1))
    return strftime("%Y-%m-%dT%H:%M:%SZ", gmtime()-'2HOURS')

I tried this:

def two_hours_ago():
    """Return correctly formatted timestamp"""
    today = date.today()
    yesterday = (today - timedelta(hours=2))
    print(yesterday.timetuple())
    return strftime("%Y-%m-%dT%H:%M:%SZ", yesterday.timetuple())

UPDATE thank you Huang Yen Hao

I was looking for a 2 hour interval returned in ISO format for Amazon MWS, I used the following functions to return the correctly formatted time.

def two_hours_ago():
    """Return correctly formatted timestamp"""
    now = datetime.now()
    two_hours_ago = (now - timedelta(hours=2))
    return two_hours_ago.strftime("%Y-%m-%dT%H:%M:%SZ")
def now():
    """Return correctly formatted timestamp"""
    now = datetime.now()
    two_hours_ago = (now - timedelta(hours=0))
    return two_hours_ago.strftime("%Y-%m-%dT%H:%M:%SZ")

I don't really understand the code that is today = date.today() .

Is it means, for example, 2017/10/18 00:00:00?

The following code can get time two hours ago. I am not sure what you what is it or not..

from datetime import datetime, timedelta

def two_hours_ago():
    """Return correctly formatted timestamp"""
    now = datetime.now()
    two_hours_ago = (now - timedelta(hours=2))
    return two_hours_ago.strftime("%Y-%m-%dT%H:%M:%SZ")

For this code, it will perform like following

>>> two_hours_ago()
'2017-10-19T11:28:40Z'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM