import datetime as dt
import re
import time
from typing import List, cast
import pytz
[docs]
class DateTimeConverter:
# When adding pattern here put the pattern with most information on top
_patterns = ["%Y-%m-%dT%H:%M:%S.%fZ", "%Y-%m-%dT%H:%M:%SZ", "%Y-%m-%d"]
utc_offset_re = re.compile(r"([\+-])(\d+)$")
multiSpace_re = re.compile(r"( {2,})")
[docs]
@classmethod
def convertDateTime(cls, entry: str):
entry = re.sub(cls.multiSpace_re, " ", entry)
match = cls.utc_offset_re.search(entry)
if match and len(match.group(2)) == 3:
entry = entry.replace(match.group(0), match.group(1) + "0" + match.group(2))
dates: List[dt.datetime] = []
for pattern in set(cast(List[str], cls._patterns)):
try:
dates.append(dt.datetime.strptime(entry, pattern))
except:
continue
if len(dates) < 1:
return None
d = dates[0]
if d.tzinfo == pytz.UTC or d.tzinfo is None:
local_tz = pytz.timezone(time.tzname[0]) # Change to your local timezone
d = d.replace(tzinfo=pytz.utc).astimezone(local_tz)
return d