使用此字符串Tue Jan 10 2017 13:00:13 GMT 0800 (Taipei Standard Time)
将其转换为python日期类型对象的正确格式是什么strptime
?
我尝试了这个问题的答案,但它对我不起作用:
date1 = datetime.strptime(strDate1, '%b %d %Y %I:%M%p')
ValueError:时间数据'2017年1月10日星期二13:00:13 GMT 0800(台北标准时间)'与格式'%b%d%Y%I%I:%M%p'不匹配
通常,您希望能够使用%z(小写字母z)转换TZ偏移,但是对此的支持是粗略的。所以你可以自己动手做:
import datetime as dt
import re
PARSE_TIMESTAMP = re.compile('(.*) ([+-]?\d+) \(.*\)$')
def my_datetime_parse(timestamp):
''' return a naive datetime relative to UTC '''
# find the standard time stamp, and the TZ offset and remove extra end
matches = PARSE_TIMESTAMP.match(timestamp).groups()
# convert the timestamp element
timestamp = dt.datetime.strptime(matches[0], '%a %b %d %Y %H:%M:%S %Z')
# calculate the timezone offset
tz_offset = matches[1]
sign = '+'
if tz_offset[0] in '-+':
sign = tz_offset[0]
tz_offset = tz_offset[1:]
tz_offset += '0' * (4 - len(tz_offset))
minutes = int(tz_offset[0:2]) * 60 + int(tz_offset[2:])
if sign == '-':
minutes = -minutes
# add the timezone offset to our time
timestamp += dt.timedelta(minutes=minutes)
return timestamp
date_string = 'Tue Jan 10 2017 13:00:13 GMT +0800 (Taipei Standard Time)'
print(my_datetime_parse(date_string))
此代码产生:
2017-01-10 21:00:13
该代码删除了,(Taipei Standard Time)
因为它与是多余的+0800
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句