1

I have a date in this format = "Tue, 28 Feb 2017 18:30:32 GMT"

I can convert it to a datetime object using time.strptime("Tue, 28 Feb 2017 18:30:32 GMT", "%a, %d %b %Y %H:%M:%S %Z") but the datetime object does not keep track of timezone.

I want to be able to to know the timezone. How can I achieve that? Any help is much appreciated.

user6037143
  • 516
  • 5
  • 20

2 Answers2

0
from dateutil import parser
parser.parse("Tue, 28 Feb 2017 18:30:32 GMT")

datetime.datetime(2017, 2, 28, 18, 30, 32, tzinfo=tzutc())

Max Power
  • 8,265
  • 13
  • 50
  • 91
  • Thanks, I know I can achieve this using in one single line using dateutil.parser. I was trying to achieve this using standard library and use an external library as a last resort. – user6037143 Apr 14 '17 at 13:54
  • In your question you showed you are willing to use time.strptime, which must be imported, except it didn't work. dateutil is also a very common library and not a heavy dependency at all, except this works. If you will not accept any answer which uses a library, or specifically will not accept any answer which uses any library except time, please specify that in your question next time. – Max Power Apr 14 '17 at 15:09
  • Gotcha! What I meant was standard library (i.e. time) and not having to install an external library (i.e. dateutil.parser). – user6037143 Apr 14 '17 at 18:43
0

This problem is actually more involved than it might first appear. I understand that timezone names are not unique and that there are throngs of the things. However, if the number of them that you need to work with is manageable, and if your inputs are limited to that format, then this approach might be good for you.

>>> from dateutil.parser import *
>>> tzinfos = {'GMT': 0, 'PST': -50, 'DST': 22 }
>>> aDate = parse("Tue, 28 Feb 2017 18:30:32 GMT", tzinfos=tzinfos)
>>> aDate.tzinfo.tzname(0)
'GMT'
>>> aDate = parse("Tue, 28 Feb 2017 18:30:32 PST", tzinfos=tzinfos)
>>> aDate.tzinfo.tzname(0)
'PST'
>>> aDate = parse("Tue, 28 Feb 2017 18:30:32 DST", tzinfos=tzinfos)
>>> aDate.tzinfo.tzname(0)
'DST'

Load the alternative timezone abbreviations into a dictionary, in this code called tzinfos then parse away. The timezone parsed from the date expression becomes available in the construct shown.

Other date items are available, as you would expect.

>>> aDate.day
28
>>> aDate.month
2
>>> aDate.year
2017
Bill Bell
  • 21,021
  • 5
  • 43
  • 58