-1

I have two string like these:

"Sun 10 May 2015 13:54:36 -0700"
"Sun 10 May 2015 13:54:36 +0000"

(The last part is time zone -0700 means 7 hours less than GMT)
My intention is turn it to a unix timestamp to find their absolute difference easily.

My Question is is there a built-in method for turning these formated texts to Unix timestamp? Or Is there a one that computes difference of two such strings directly??

Edit: This Question differs from This one since that problem doesn't include time zones and not any of answers to that question mentioned anything about time zone.

Community
  • 1
  • 1
FazeL
  • 916
  • 2
  • 13
  • 30
  • @schwobaseggl I couldn't find my answer in the question you mentioned, since no one told anything about time zones there :-( – FazeL May 29 '16 at 10:49
  • 2
    What about http://stackoverflow.com/questions/1101508/how-to-parse-dates-with-0400-timezone-string-in-python? – user2390182 May 29 '16 at 10:49
  • @schwobaseggl the dateutil seems perfect but it is not bundled with python standard library, I will edit the question properly. – FazeL May 29 '16 at 10:53
  • Which version of python are you using? – Vishwa May 29 '16 at 10:54
  • @Vishwa I use hackerrank.com python2 or I could use python 3 If it solves any problem – FazeL May 29 '16 at 10:57
  • @schwobaseggl one of the answers in http://stackoverflow.com/questions/1101508/how-to-parse-dates-with-0400-timezone-string-in-python actually works with datetime module only , but just with python 3.2+ I could use that , Thank you. – FazeL May 29 '16 at 11:03

2 Answers2

1

This should work on Python 3 & above but not known to work on all platforms on Python 2.

date_str = "Sun 10 May 2015 13:54:36 -0700"
pattern =  '%a %d %B %Y %H:%M:%S %z'
dt = int(time.mktime(time.strptime(date_str ,pattern )))
print(dt)

For, Python 2.7+, (without %z)

import datetime
date_str = "Sun 10 May 2015 13:54:36 -0700"

dt_str = date_str[:-5].strip()
dt_zone = int(date_str[-5:])/100
pattern =  '%a %d %B %Y %H:%M:%S'

dtobj = datetime.datetime.strptime(dt_str ,pattern)
dt = dtobj + datetime.timedelta(hours=dt_zone)
print( dt.strftime('%s') )
Vishwa
  • 1,525
  • 2
  • 13
  • 25
0

This code answer to your question:

from datetime import timedelta, datetime, tzinfo
date1="Sun 10 May 2015 13:54:36 -0700"   

date2=date1[4:-6]

zone = int(date1[-5:])/100

d=datetime.strptime(date2, "%d %B %Y %H:%M:%S")

class TZ(tzinfo):
   def utcoffset(self, dt): return timedelta(hours=zone)

d=datetime(d.year, d.month, d.day,d.hour,d.minute,d.second, tzinfo=TZ()).isoformat(' ')


print d
khelili miliana
  • 3,730
  • 2
  • 15
  • 28