From: Menno Smits Date: Mon, 29 Jun 2015 22:52:02 +0000 (+1200) Subject: Support dot as the time separator in timestamp strings X-Git-Tag: 0.13~1^2~10 X-Git-Url: http://git.khamidou.com/?a=commitdiff_plain;h=2fc0393362fbc32550ba08d6004c30ca49827397;p=imapclient.git Support dot as the time separator in timestamp strings This is unconventional but has been seen in the wild. Fixes #154. --- diff --git a/imapclient/datetime_util.py b/imapclient/datetime_util.py index 10758d4..bb807b4 100644 --- a/imapclient/datetime_util.py +++ b/imapclient/datetime_util.py @@ -4,6 +4,7 @@ from __future__ import unicode_literals +import re from datetime import datetime from email.utils import parsedate_tz @@ -19,8 +20,7 @@ def parse_to_datetime(timestamp, normalise=True): If normalise is False, then the returned datetime will be unadjusted but will contain timezone information as per the input. """ - timestamp = timestamp.decode('latin-1') # parsedate_tz only works with strings - time_tuple = parsedate_tz(timestamp) + time_tuple = parsedate_tz(_normalise(timestamp)) if time_tuple == None: raise ValueError("couldn't parse datetime %r" % timestamp) @@ -37,3 +37,14 @@ def parse_to_datetime(timestamp, normalise=True): def datetime_to_native(dt): return dt.astimezone(FixedOffset.for_system()).replace(tzinfo=None) + + +# Matches timestamp strings where the time separator is a dot (see +# issue #154). For example: 'Sat, 8 May 2010 16.03.09 +0200' +_rfc822_dotted_time = re.compile("\w+, ?\d{1,2} \w+ \d\d(\d\d)? \d\d?\.\d\d?\.\d\d?.*") + +def _normalise(s): + s = s.decode('latin-1') # parsedate_tz only works with strings + if _rfc822_dotted_time.match(s): + return s.replace(".", ":") + return s diff --git a/imapclient/test/test_datetime_util.py b/imapclient/test/test_datetime_util.py index fb6deba..38b2f61 100644 --- a/imapclient/test/test_datetime_util.py +++ b/imapclient/test/test_datetime_util.py @@ -35,5 +35,20 @@ class TestParsing(unittest.TestCase): datetime(2007, 2, 9, 17, 8, 8, 0, FixedOffset(-4*60 - 30)) ) + def test_dots_for_time_separator(self): + # As reported in issue #154. + self.check_normalised_and_not( + b'Sat, 8 May 2010 16.03.09 +0200', + datetime(2010, 5, 8, 16, 3, 9, 0, FixedOffset(120)) + ) + self.check_normalised_and_not( + b'Tue, 18 May 2010 16.03.09 -0200', + datetime(2010, 5, 18, 16, 3, 9, 0, FixedOffset(-120)) + ) + self.check_normalised_and_not( + b'Wednesday,18 August 2010 16.03.09 -0200', + datetime(2010, 8, 18, 16, 3, 9, 0, FixedOffset(-120)) + ) + def test_invalid(self): self.assertRaises(ValueError, parse_to_datetime, b'ABC')