I have a string time coming from a third party (external to my python program), and I need to compare that time to right now. How long ago was that time?
How can I do this?
I've looked at the datetime and time libraries, as well as pytz, and can't find an obvious way to do this. It should automatically incorporate DST because the third party doesn't explicitly state its offset, only the timezone (US/Eastern).
Good question Zack! I've had this problem myself.
Here's some code to do so:
from datetime import datetime import time import calendar import pytz def howLongAgo(thirdPartyString, timeFmt): # seconds since epoch thirdPartySeconds = calendar.timegm(time.strptime(thirdPartyString, timeFmt)) nowSecondsUTC = time.time() # hour difference with DST nowEastern = datetime.now(pytz.timezone('US/Eastern')) nowUTC = datetime.now(pytz.timezone('UTC')) timezoneOffset = (nowEastern.day - nowUTC.day)*24 + (nowEastern.hour - nowUTC.hour) + (nowEastern.minute - nowUTC.minute)/60.0 thirdPartySecondsUTC = thirdPartySeconds - (timezoneOffset * 60 * 60) return nowSecondsUTC - thirdPartySecondsUTC howLongAgo('June 09, 2016 at 06:22PM', '%B %d, %Y at %I:%M%p') # first argument always provided in ET, either EDT or EST