Search code examples
pythondatetimeutctimestamp

Python storing and comparing timestamps


From what I've researched, it appears storing my timestamps as UTC (not native, full, eg: 2013-01-29 02:11:11.151996+00:00) is the norm.

When retrieving the times, I want to check if a window of time has elapsed. So,

currentTime = datetime.utcnow()
storedTime  = '2013-01-29 02:11:11.151996+00:00'

if (storedTime + 60) > currentTime:
    print "60 or more has elapsed, do something again"

How can I add arbitrary amounts of time do a UTC timestamp, even if it's not a datetime object? Or, how do I create a datetime object from a UTC timestamp, and then add arbirary time to it.

I know once I have two datetime objects I can do d1 > d2. I'm just having trouble getting the objects.

TIA!

Edit/Update:

Thanks everyone. I decided to do the following: (which is a combination of both answers, sorry I can only accept one!)

        lastTime = dateutil.parser.parse(subDict['last'])
        utcNow = datetime.datetime.utcnow().replace(tzinfo=tz.tzutc())

        if lastTime + datetime.timedelta(seconds=subDict['interval']) < utcNow:
            print "Time elapsed, do something!"

Solution

  • Put storedTime as a datetime object and add a timedelta. strptime is used to parse a string to a datetime object:

    (Refer to the link for the details of the format string)

    currentTime = datetime.datetime.utcnow()
    s = '2013-01-29 02:11:11.151996+00:00'
    storedTime = datetime.datetime.strptime(s[:-6], "%Y-%m-%d %H:%M:%S.%f")
    if storedTime + datetime.timedelta(minutes=60) > currentTime:
        print "stuff..."
    

    NOTE: from 3.7 .fromisoformat() was added, so there is no need to use strptime for isoformat() datetime strings.

    >>> datetime.datetime.fromisoformat('2013-01-29 02:11:11.151996+00:00')
    datetime.datetime(2013, 1, 29, 2, 11, 11, 151996, tzinfo=datetime.timezone.utc)