Yaro
Yaro

Reputation: 75

Date parsing and formating in Python 2.7

I'm looking to do what may seem like an easy task but I find it to be an awful nightmare in Python 2.7.

I have a date string such as Sat, 13 Dec 2014 13:52:00 -0500 to Dec 13 2014, 13:52 am EST

Any idea how I could achieve this, preferably without doing to much coding and logic implementation, but rather using a built in functionality or a popular 3rd party lib?

Note: my timezone is not EST.

The closest I've come to is:

import time
import email.utils

observationTime = email.utils.parsedate('Sat, 13 Dec 2014 13:52:00 -0500')
print time.strftime('%b %d %Y %H:%M %p %Z', observationTime)

But it produces:

Dec 13 2014 13:52 PM GMT Daylight Time

Upvotes: 1

Views: 1597

Answers (1)

unutbu
unutbu

Reputation: 879191

You could use dateutil to parse the date string into a timezone-aware datetime:

import dateutil.parser as DP
observationTime = DP.parse('Sat, 13 Dec 2014 13:52:00 -0500')
# datetime.datetime(2014, 12, 13, 13, 52, tzinfo=tzoffset(None, -18000))

Now, to print the timezone abbreviation EST requires that you convert the timezone-aware datetime to the 'US/Eastern' timezone. This can be done using pytz.

This can not be done automatically since there are other timezones, such as 'America/Bogota', which have the same utcoffset.

import pytz
eastern = pytz.timezone('US/Eastern')
observationTime = observationTime.astimezone(eastern)
print(observationTime.strftime('%b %d %Y %H:%M %p %Z'))
# Dec 13 2014 13:52 PM EST
print(observationTime.strftime('%b %d %Y %H:%M %z'))
# Dec 13 2014 13:52 -0500

bogota = pytz.timezone('America/Bogota')
observationTime = observationTime.astimezone(bogota)
print(observationTime.strftime('%b %d %Y %H:%M %p %Z'))
# Dec 13 2014 13:52 PM COT
print(observationTime.strftime('%b %d %Y %H:%M %z'))
# Dec 13 2014 13:52 -0500

(Note 13:52 is PM, not AM...)

Upvotes: 2

Related Questions