-
三国纷争
如果你得到像这样的 ISO 8601 字符串:“2016-08-15T07:50:12”,我觉得最简单的方法是使用 dateutil 来转换它。import dateutil.parser
yourdate = dateutil.parser.parse(datestring)
-
温温酱
下面的代码片段可能对您正在寻找的有帮助from datetime import datetimefmt='%Y-%m-%dT%H:%M:%S'dt="2016-08-15T07:50:12"datetime.strptime(dt, fmt)datetime.datetime(2016, 8, 15, 7, 50, 12)fmt1='%Y-%m-%dT%H:%M:%S.%f'dt1="2016-08-15T07:50:12.34" datetime.strptime(dt1, fmt1)datetime.datetime(2016, 8, 15, 7, 50, 12, 340000)通过添加简单的条件语句你就能实现。
-
慕运维8079593
您需要先解析不带时区的日期,然后再添加时区。不幸的是你需要为此子类化 tzinfo 。您可以使用下面的代码并根据您的要求进行相应的更改。from datetime import datetime, timedelta, tzinfoclass FixedOffset(tzinfo): """offset_str: Fixed offset in str: e.g. '-0400'""" def __init__(self, offset_str): sign, hours, minutes = offset_str[0], offset_str[1:3], offset_str[3:] offset = (int(hours) * 60 + int(minutes)) * (-1 if sign == "-" else 1) self.__offset = timedelta(minutes=offset) # NOTE: the last part is to remind about deprecated POSIX GMT+h timezones # that have the opposite sign in the name; # the corresponding numeric value is not used e.g., no minutes '<%+03d%02d>%+d' % (int(hours), int(minutes), int(hours)*-1) def utcoffset(self, dt=None): return self.__offset def tzname(self, dt=None): return self.__name def dst(self, dt=None): return timedelta(0) def __repr__(self): return 'FixedOffset(%d)' % (self.utcoffset().total_seconds() / 60)date_with_tz = "2017-01-12T14:12:06.000-0500"date_str, tz = date_with_tz[:-5], date_with_tz[-5:]dt_utc = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S.%f")dt = dt_utc.replace(tzinfo=FixedOffset(tz))print(dt)