Last active
November 19, 2018 10:48
-
-
Save SamuelePilleri/3ffae24b3cdd6dd04d01790519c2846b to your computer and use it in GitHub Desktop.
Convert an asctime datetime format to a dfdatetime string format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import re | |
examples = [ | |
'Wed, 07 Feb 2018 09:26:19 +0000 (UTC)', | |
'Sat, 08 Sep 2018 18:56:22', | |
'Tue, 06 Mar 2018 11:20:03 +0000', | |
'11 Sep 2017 20:51:44 +0100', | |
'13 Dec 2016 13:46:28 -0800 (PST)', | |
'Wed, 07 Feb 2018 09:26:19 +0000 (added by pippo)', | |
'Wed, 7 Feb 2018 09:26:19 +0000 (UTC)', | |
'1 Sep 2017 20:51:44 +0100' | |
] | |
asctime_pattern = re.compile( | |
r'(?P<day>\d{1,2})\s+' | |
r'(?P<month>Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+' | |
r'(?P<year>\d{4})\s+' | |
r'(?P<hour>\d{1,2}):(?P<minute>\d{1,2}):(?P<second>\d{1,2})' | |
r'(?:\s+(?P<timezone>[+-]\d{4}))?') | |
timezone_pattern = re.compile(r'([+-]\d{2})(\d{2})') | |
month_lookup_table = { | |
'Jan': 1, 'Feb': 2, 'Mar': 3, | |
'Apr': 4, 'May': 5, 'Jun': 6, | |
'Jul': 7, 'Aug': 8, 'Sep': 9, | |
'Oct': 10, 'Nov': 11, 'Dec': 12 | |
} | |
for example in examples: | |
match = re.search(asctime_pattern, example) | |
print('{0} --> {1:4s}-{2:02d}-{3:0>2s} {4:0>2s}:{5:0>2s}:{6:0>2s}.000{7}'.format( | |
example, | |
match.group('year'), month_lookup_table[match.group('month')], match.group('day'), | |
match.group('hour'), match.group('minute'), match.group('second'), | |
re.sub(timezone_pattern, r'\1:\2', match.group('timezone') or '+0000') | |
)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment