python - 在 python 3.3 中使用时区更新的字符串

标签 python datetime python-3.x

如果我使用代码修剪时区数据,我可以转换以下日期时间:

print(datetime.datetime.strptime(cc.text[:25],"%Y-%m-%dT%H:%M:%S.%f"))

但是,当我将 %z 或 %Z 与时区数据一起使用时,我收到以下错误,您能否让我明白我哪里出错了,我使用的是 python 3.3,%z 应该可以在

print(datetime.datetime.strptime(cc.text,"%Y-%m-%dT%H:%M:%S.%f%z"))

错误:

ValueError: time data '2014-09-16T19:26:18.5455599+05:30' does not match format '%Y-%m-%dT%H:%M:%S.%f%Z'

最佳答案

有两个问题:

  • 毫秒部分的长度有 7 位,但 Python 期望为 6 位。
  • 时区偏移包含一个 : 冒号。

删除这两个额外的字符使 strptime() 工作:

>>> import datetime
>>> cctext = '2014-09-16T19:26:18.5455599+05:30'
>>> cctext[:-7] + cctext[-6:-3] + cctext[-2:]
'2014-09-16T19:26:18.545559+0530'
>>> datetime.datetime.strptime(cctext[:-7] + cctext[-6:-3] + cctext[-2:], "%Y-%m-%dT%H:%M:%S.%f%z")
datetime.datetime(2014, 9, 16, 19, 26, 18, 545559, tzinfo=datetime.timezone(datetime.timedelta(0, 19800)))

关于python - 在 python 3.3 中使用时区更新的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25870596/

相关文章:

c# - 如何改进 WPF 倒数计时器的时间格式

python - 根据某些标准查找列表的共同元素?

python-3.x - 在 Mac OS 10.8 上的 Anaconda 中更改默认 Python 环境(从 2.7 到 3.3)

python - 无法通过django中定义的url获取对象

python-3.x - 无法在 M1 Mac 上使用 Pip 安装 OpenCV

python - 选择 "other value"的通用方法

python - 更新指向 settings.AUTH_USER_MODEL 的关系

python - 在 Python 上将数组、字典、列表打印到文本文件中

python - 如何在 Mac OSX 上确定文件的扩展属性和资源分支及其大小?

c# - LINQ to Entities DateTime 不一致