使用strptime将字符串转换为具有时区偏移的python日期类型对象

劳尔

使用此字符串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'不匹配

斯蒂芬·劳赫(Stephen Rauch)

通常,您希望能够使用%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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将具有时区的字符串转换为utc datetime对象python

将具有UTC偏移量的字符串转换为日期时间对象

将具有时区值的日期时间字符串转换为印度标准时间(IST)

将带有时区的时间日期字符串转换为 utc python

Python:将具有不同时区的时间字符串转换为主机时区datetime对象?

如何将不知道的日期时间字符串转换为具有时区的已知日期时间对象?

将字符串转换为日期python strptime错误

将日期值(字符串)转换为具有不同时区的时间戳

如何在python中将带有时区的日期字符串转换为日期时间

使用 datetime.strptime 将字符串转换为日期时 Python 中的值错误

使用毫秒和时区将字符串转换为日期时间-Python

使用时刻时区js将日期字符串转换为带时区的日期

将仅具有年份(有时)的ac#字符串转换为日期时间

将时区pytz字符串转换为python / django中的偏移量

接收包括字符串的时区偏移量的日期,并使用该时区转换为其他格式

如何将带有时区的字符串转换为Unix时间戳Python?

将带有时区的python datetime转换为字符串

将字符串转换为具有几天可变数字的日期时间对象

如何将具有当前 GMT 时区的字符串转换为正常日期时间

如何将具有Etc / GMT的日期字符串转换为Python日期时间?

Python使用时区偏移量转换日期/时间字符串

使用具有不同日期格式的电话将字符串转换为日期

如何在没有时区偏移的情况下将日期转换为毫秒?

如何将 ORACLE 日期和时间戳类型转换为带时区的字符串?

将字符串转换为带时区的日期时间

将字符串转换为类型对象-Python

将字符串日期转换为对象会产生无效的时区指示符“ 0”

如何将祖鲁时区字符串转换为特定的日期时间对象?

解析具有时区偏移值的ZonedDateTime字符串