使用strtime将字符串转换为具有时区偏移量的python日期类型对象
使用使用strtime将字符串转换为具有时区偏移量的python日期类型对象,python,datetime,strptime,Python,Datetime,Strptime,使用strtime将此字符串2017年1月10日星期二13:00:13 GMT 0800(台北标准时间)转换为python日期类型对象的正确格式是什么 我尝试了这个答案,但它对我不起作用: date1 = datetime.strptime(strDate1, '%b %d %Y %I:%M%p') ValueError:时间数据'2017年1月10日星期二13:00:13 GMT 0800(台北 标准时间)“”与格式“%b%d%Y%I:%M%p”不匹配 您可以格式化不带时区的日期,然后再添加
strtime
将此字符串2017年1月10日星期二13:00:13 GMT 0800(台北标准时间)
转换为python日期类型对象的正确格式是什么
我尝试了这个答案,但它对我不起作用:
date1 = datetime.strptime(strDate1, '%b %d %Y %I:%M%p')
ValueError:时间数据'2017年1月10日星期二13:00:13 GMT 0800(台北
标准时间)“”与格式“%b%d%Y%I:%M%p”不匹配
您可以格式化不带时区的日期,然后再添加
import pytz
date1=datetime.strptime('Tue Jan 10 2017 13:00:13', '%a %b %d %Y %H:%M:%S')
tz=pytz.timezone('Asia/Taipei')
tz.localize(date1)
名义上,您希望能够使用%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
代码删除了
(台北标准时间)
,因为它与+0800
是冗余的。我正在尝试删除时区,因为字符串是javascriptnew Date()
object。我不确定我是否正确理解了您的意思,您想要类似的datetime.strtime(strDate1[:24],格式)吗
?切片字符串不会坏吗?假设该字符串的长度可能会更改吗?我将尝试此方法如果您想尝试拆分而不是切片,您可以尝试使用此'.join(strDate1.split()[:5])
这将适用于动态日期时间字符串格式?此代码假设有一个带有的括号字段(额外内容)
在需要删除的末尾。它还假设存在需要解析的时区偏移量。如果更好地支持%z格式,则可以使用该格式完成此操作。