Blaise
Blaise

Reputation: 7518

Comparing dates in Python - how to handle time zone modifiers

I am doing Python date comparizon:

Assume I have a date like this: 'Fri Aug 17 12:34:00 2012 +0000'

I am parsing it in the following manner:

dt=datetime.strptime('Fri Aug 17 12:34:00 2012 +0000', '%a %b %d %H:%M:%S %Y +0000')

I could not find on the documentation page how to handle the remaining +0000? I want to have a more generic solution then hardcoded value.

Perhaps this is quite easy, any hint?

Upvotes: 0

Views: 490

Answers (3)

Mahdi Yusuf
Mahdi Yusuf

Reputation: 21028

You might want also give Delorean a look. Which is a wrapper around both pytz and dateutil it provides timezone manipulation as well as easy datetime time zone shift.

Here is how I would solve your question with Delorean.

>>> from delorean import parse
>>> parse("2011/01/01 00:00:00 -0700")
Delorean(datetime=2011-01-01 07:00:00+00:00, timezone=UTC)

From there you can return the datetime by simply return the .datetime attribute. If you wan to do some time shifts simply use the Delorean object and do .shift("UTC") etc.

Upvotes: 3

Martijn Pieters
Martijn Pieters

Reputation: 1121914

The default datetime module does not handle timezones very well; beyond your current machine timezone and UTC, they are basically not supported.

You'll have to use an external library for that or handle the timezone offset manually.

External library options:

  • Use dateutil.parser can handle just about any date and or time format you care to throw at it:

    from dateutil import parser
    
    dt = parser.parse(s)
    
  • The iso8601 library handles only ISO 8601 formats, which include timezone offsets of the same form:

    import iso8601
    datetimetext, tz = s.rsplit(None, 1)  # only grab the timezone portion.
    timezone = iso8601.iso8601.parse_timezone('{}:{}'.format(tz[:3], tz[3:]))
    dt = datetime.strptime(datetimetext, '%a %b %d %H:%M:%S %Y').replace(tzinfo=timezone)
    

Demonstration of each approach:

>>> import datetime
>>> s = 'Fri Aug 17 12:34:00 2012 +0000'
>>> import iso8601
>>> timezone = iso8601.iso8601.parse_timezone('{}:{}'.format(tz[:3], tz[3:]))
>>> datetime.datetime.strptime(datetimetext, '%a %b %d %H:%M:%S %Y').replace(tzinfo=timezone)
datetime.datetime(2012, 8, 17, 12, 34, tzinfo=<FixedOffset '+00:00'>)
>>> from dateutil import parser
>>> parser.parse(s)
datetime.datetime(2012, 8, 17, 12, 34, tzinfo=tzutc())

Upvotes: 5

isedev
isedev

Reputation: 19601

Use the dateutil.parser:

>>> import dateutil.parser
>>> dateutil.parser.parse('Fri Aug 17 12:34:00 2012 +0000')
>>> datetime.datetime(2012, 8, 17, 12, 34, tzinfo=tzutc())

Upvotes: 1

Related Questions