Zack Coburn Zack Coburn - 1 year ago 76
Python Question

String time with timezone compared to now, in python?

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

Answer Source

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 ='US/Eastern'))
  nowUTC ='UTC'))
  timezoneOffset = ( -*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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download