Alex Amato
Alex Amato

Reputation: 1591

How do I parse timezones from dates in python

Here's what I have tried so far. I'm just not too sure as to why it outputs as PST instead of GMT. I'm not sure if that's not the correct way to parse it, or to output it. Something seems to be wrong somewhere.

>>> x = time.strptime('Wed, 27 Oct 2010 22:17:00 GMT', '%a, %d %b %Y %H:%M:%S %Z')

>>> time.strftime('%a, %d %b %Y %H:%M:%S %Z', x)

'Wed, 27 Oct 2010 22:17:00 PST'

Appreciate any help,

Upvotes: 1

Views: 156

Answers (2)

ars
ars

Reputation: 123588

See the docs on strftime behavior:

%Z

If tzname() returns None, %Z is replaced by an empty string. Otherwise %Z is replaced by the returned value, which must be a string.

The dateutil may be used for parsing timezones. Also see the pytz library if you're going to be working with timezones, though it may not be necessary for what you're doing.

Upvotes: 1

mouad
mouad

Reputation: 70089

First of all i recommend that you use dateutil

>>> import dateutil.parser

>>> x = dateutil.parser.parse('Wed, 27 Oct 2010 22:17:00 GMT')
datetime.datetime(2010, 10, 27, 22, 17, tzinfo=tzutc())
>>> str(x)
'2010-10-27 22:17:00+00:00'
>>> x.strftime('%a, %d %b %Y %H:%M:%S %Z')
'Wed, 27 Oct 2010 22:17:00 UTC'

Upvotes: 2

Related Questions