mr-sk
mr-sk

Reputation: 13397

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!"

Upvotes: 1

Views: 11664

Answers (2)

monkut
monkut

Reputation: 43832

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)

Upvotes: 4

David S
David S

Reputation: 13851

For the parsing side of things, I like to use dateutil module. To me it's just easier and cleaner than the strptime solution presented (although that should work).

import dateutil.parser

stored_time = dateutil.parser.parse('2013-01-29 02:11:11.151996+00:00')

But, that's the easy part! :) you are going to run into problems now trying to compare native and timezone aware values. There have been several SO questions dealing with this. You might want to read of the answer for this one here.

Upvotes: 3

Related Questions