Alex Rivera | Logout

How to parse dates with -0400 timezone string in Python?

Asked 2009-07-09T02:19:03.097
100

I have a date string of the form '2009/05/13 19:19:30 -0400'. It seems that previous versions of Python may have supported a %z format tag in strptime for the trailing timezone specification, but 2.6.x seems to have removed that.

What's the right way to parse this string into a datetime object?

Edit
Report

1 Answer

7

The problem with using dateutil is that you can't have the same format string for both serialization and deserialization, as dateutil has limited formatting options (only dayfirst and yearfirst).

In my application, I store the format string in .INI file, and each deployment can have its own format. Thus, I really don't like the dateutil approach.

Here's an alternative method that uses pytz instead:

from datetime import datetime, timedelta

from pytz import timezone, utc
from pytz.tzinfo import StaticTzInfo

class OffsetTime(StaticTzInfo):
    def __init__(self, offset):
        """A dumb timezone based on offset such as +0530, -0600, etc.
        """
        hours = int(offset[:3])
        minutes = int(offset[0] + offset[3:])
        self._utcoffset = timedelta(hours=hours, minutes=minutes)

def load_datetime(value, format):
    if format.endswith('%z'):
        format = format[:-2]
        offset = value[-5:]
        value = value[:-5]
        return OffsetTime(offset).localize(datetime.strptime(value, format))

    return datetime.strptime(value, format)

def dump_datetime(value, format):
    return value.strftime(format)

value = '2009/05/13 19:19:30 -0400'
format = '%Y/%m/%d %H:%M:%S %z'

assert dump_datetime(load_datetime(value, format), format) == value
assert datetime(2009, 5, 13, 23, 19, 30, tzinfo=utc) \
    .astimezone(timezone('US/Eastern')) == load_datetime(value, format)
answered 2013-03-20T05:41:41.853

Your Answer