使用 strptime 将带有偏移量的时间戳转换为 datetime obj [英] Convert timestamps with offset to datetime obj using strptime

查看:43
本文介绍了使用 strptime 将带有偏移量的时间戳转换为 datetime obj的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试转换格式为2012-07-24T23:14:29-07:00"的时间戳使用 strptime 方法到 python 中的日期时间对象.问题在于最后的时间偏移(-07:00).没有偏移我可以成功

time_str = "2012-07-24T23:14:29"time_obj=datetime.datetime.strptime(time_str,'%Y-%m-%dT%H:%M:%S')

但是我尝试了偏移量

time_str = "2012-07-24T23:14:29-07:00"time_obj=datetime.datetime.strptime(time_str,'%Y-%m-%dT%H:%M:%S-%z').

但是它给出了一个值错误,说z"是一个错误的指令.

有什么解决方法的想法吗?

解决方案

Python 2 strptime() 函数确实不支持时区的 %z 格式(因为底层 time.strptime() 函数不支持).您有两个选择:

  • 使用strptime解析时忽略时区:

    time_obj = datetime.datetime.strptime(time_str[:19], '%Y-%m-%dT%H:%M:%S')

  • 使用dateutil模块,它是解析函数是否处理时区:

    from dateutil.parser import parsetime_obj = 解析(time_str)

命令提示符下的快速演示:

<预><代码>>>>从 dateutil.parser 导入解析>>>解析(2012-07-24T23:14:29-07:00")datetime.datetime(2012, 7, 24, 23, 14, 29, tzinfo=tzoffset(None, -25200))

您也可以升级到 Python 3.2 或更高版本,其中时区支持已改进到 %z 可以工作的程度,前提是您从输入,以及 %z 之前的 -:

<预><代码>>>>导入日期时间>>>time_str = "2012-07-24T23:14:29-07:00">>>datetime.datetime.strptime(time_str, '%Y-%m-%dT%H:%M:%S%z')回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中文件/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.4/_strptime.py",第500行,_strptime_datetimett, 分数 = _strptime(data_string, 格式)文件/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.4/_strptime.py",第 337 行,在 _strptime(数据字符串,格式))ValueError: 时间数据 '2012-07-24T23:14:29-07:00' 与格式 '%Y-%m-%dT%H:%M:%S%z' 不匹配>>>''.join(time_str.rsplit(':', 1))'2012-07-24T23:14:29-0700'>>>datetime.datetime.strptime(''.join(time_str.rsplit(':', 1)), '%Y-%m-%dT%H:%M:%S%z')datetime.datetime(2012, 7, 24, 23, 14, 29, tzinfo=datetime.timezone(datetime.timedelta(-1, 61200)))

I am trying to convert time-stamps of the format "2012-07-24T23:14:29-07:00" to datetime objects in python using strptime method. The problem is with the time offset at the end(-07:00). Without the offset i can successfully do

time_str = "2012-07-24T23:14:29"

time_obj=datetime.datetime.strptime(time_str,'%Y-%m-%dT%H:%M:%S')

But with the offset i tried

time_str = "2012-07-24T23:14:29-07:00"

time_obj=datetime.datetime.strptime(time_str,'%Y-%m-%dT%H:%M:%S-%z').

But it gives a Value error saying "z" is a bad directive.

Any ideas for a work around?

解决方案

The Python 2 strptime() function indeed does not support the %z format for timezones (because the underlying time.strptime() function doesn't support it). You have two options:

  • Ignore the timezone when parsing with strptime:

    time_obj = datetime.datetime.strptime(time_str[:19], '%Y-%m-%dT%H:%M:%S')
    

  • use the dateutil module, it's parse function does deal with timezones:

    from dateutil.parser import parse
    time_obj = parse(time_str)
    

Quick demo on the command prompt:

>>> from dateutil.parser import parse
>>> parse("2012-07-24T23:14:29-07:00")
datetime.datetime(2012, 7, 24, 23, 14, 29, tzinfo=tzoffset(None, -25200))

You could also upgrade to Python 3.2 or newer, where timezone support has been improved to the point that %z would work, provided you remove the last : from the input, and the - from before the %z:

>>> import datetime
>>> time_str = "2012-07-24T23:14:29-07:00"
>>> datetime.datetime.strptime(time_str, '%Y-%m-%dT%H:%M:%S%z')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.4/_strptime.py", line 500, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.4/_strptime.py", line 337, in _strptime
    (data_string, format))
ValueError: time data '2012-07-24T23:14:29-07:00' does not match format '%Y-%m-%dT%H:%M:%S%z'
>>> ''.join(time_str.rsplit(':', 1))
'2012-07-24T23:14:29-0700'
>>> datetime.datetime.strptime(''.join(time_str.rsplit(':', 1)), '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2012, 7, 24, 23, 14, 29, tzinfo=datetime.timezone(datetime.timedelta(-1, 61200)))

这篇关于使用 strptime 将带有偏移量的时间戳转换为 datetime obj的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆