>>> datetime.datetime.strptime("2008-08-12T12:20:30.656234Z", "%Y-%m-%dT%H:%M:%S.Z")ValueError: time data did not match format: data=2008-08-12T12:20:30.656234Z fmt=%Y-%m-%dT%H:%M:%S.Z
def from_utc(utcTime,fmt="%Y-%m-%dT%H:%M:%S.%fZ"):"""Convert UTC time string to time.struct_time"""# change datetime.datetime to time, return time.struct_time typereturn datetime.datetime.strptime(utcTime, fmt)
from datetime import datetime
def parse_rfc3339(datetime_str: str) -> datetime:try:return datetime.strptime(datetime_str, "%Y-%m-%dT%H:%M:%S.%f%z")except ValueError:# Perhaps the datetime has a whole number of seconds with no decimal# point. In that case, this will work:return datetime.strptime(datetime_str, "%Y-%m-%dT%H:%M:%S%z")
import re# this regex removes all colons and all# dashes EXCEPT for the dash indicating + or - utc offset for the timezoneconformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)datetime.datetime.strptime(conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" )
如果您的系统不支持%z strptime指令(您会看到类似ValueError: 'z' is a bad directive in format '%Y%m%dT%H%M%S.%f%z'的内容),那么您需要手动从Z(UTC)偏移时间。注意%z可能无法在Python版本<3的系统上工作,因为它取决于c库支持,该库支持因系统/python构建类型(即Jython、Cython等)而异。
import reimport datetime
# this regex removes all colons and all# dashes EXCEPT for the dash indicating + or - utc offset for the timezoneconformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)
# split on the offset to remove it. use a capture group to keep the delimitersplit_timestamp = re.split(r"[+|-]",conformed_timestamp)main_timestamp = split_timestamp[0]if len(split_timestamp) == 3:sign = split_timestamp[1]offset = split_timestamp[2]else:sign = Noneoffset = None
# generate the datetime object without the offset at UTC timeoutput_datetime = datetime.datetime.strptime(main_timestamp +"Z", "%Y%m%dT%H%M%S.%fZ" )if offset:# create timedelta based on offsetoffset_delta = datetime.timedelta(hours=int(sign+offset[:-2]), minutes=int(sign+offset[-2:]))# offset datetime with timedeltaoutput_datetime = output_datetime + offset_delta
#!/usr/bin/env pythonfrom __future__ import with_statement, division, print_functionimport sqlite3import datetime
testtimes = ["2016-08-25T16:01:26.123456Z","2016-08-25T16:01:29",]db = sqlite3.connect(":memory:")c = db.cursor()for timestring in testtimes:c.execute("SELECT strftime('%s', ?)", (timestring,))converted = c.fetchone()[0]print("%s is %s after epoch" % (timestring, converted))dt = datetime.datetime.fromtimestamp(int(converted))print("datetime is %s" % dt)
输出:
2016-08-25T16:01:26.123456Z is 1472140886 after epochdatetime is 2016-08-25 12:01:262016-08-25T16:01:29 is 1472140889 after epochdatetime is 2016-08-25 12:01:29