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

后端 未结 6 1299

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 tim

6条回答
  •  春和景丽
    2020-11-22 10:05

    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)
    

提交回复
热议问题