【问题标题】:Convert UTC time to python datetime将 UTC 时间转换为 python 日期时间
【发布时间】:2012-12-01 19:14:12
【问题描述】:

我有许多 UTC 时间戳,格式如下: 2012-04-30T23:08:56+00:00 我想将它们转换为 python 日期时间对象,但遇到了麻烦。

我的代码:

for time in data:
    pythondata[i]=datetime.strptime(time,"%y-%m-%dT%H:%M:%S+00:00")

我收到以下错误:

ValueError: time data '2012-03-01T00:05:55+00:00' does not match format '%y-%m-%dT%H:%M:%S+00:00'

看起来我的格式正确,为什么这不起作用?

【问题讨论】:

标签: python datetime utc rfc3339


【解决方案1】:

将时间格式字符串中的年份标记更改为%Y

time = '2012-03-01T00:05:55+00:00'
datetime.strptime(time, "%Y-%m-%dT%H:%M:%S+00:00")
# => datetime.datetime(2012, 3, 1, 0, 5, 55)

strftime() and strptime() behavior

【讨论】:

    【解决方案2】:

    我强烈推荐python-dateutil library,它允许将多种日期时间格式从原始字符串转换为设置/不设置时区的日期时间对象

    >>> from dateutil.parser import parse
    >>> parse('2012-04-30T23:08:56+00:00')
    
    datetime.datetime(2012, 4, 30, 23, 8, 56, tzinfo=tzutc())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-06
      • 2013-12-04
      • 2012-10-07
      • 1970-01-01
      • 2018-09-15
      • 2021-12-31
      • 2014-01-24
      • 2011-01-06
      相关资源
      最近更新 更多