如何在 Python 中使用 -0400 时区字符串解析日期? [英] How to parse dates with -0400 timezone string in Python?

查看:24
本文介绍了如何在 Python 中使用 -0400 时区字符串解析日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个格式为2009/05/13 19:19:30 -0400"的日期字符串.似乎以前版本的 Python 可能支持 strptime 中的 %z 格式标记以用于尾随时区规范,但 2.6.x 似乎已将其删除.

将此字符串解析为日期时间对象的正确方法是什么?

解决方案

你可以使用 dateutil 的 parse 函数:

<预><代码>>>>从 dateutil.parser 导入解析>>>d = 解析('2009/05/13 19:19:30 -0400')>>>ddatetime.datetime(2009, 5, 13, 19, 19, 30, tzinfo=tzoffset(None, -14400))

通过这种方式,您可以获得一个可以使用的日期时间对象.

作为 已回答,dateutil2.0 是为 Python 3.0 编写的,不适用于 Python 2.x.对于 Python 2.x,需要使用 dateutil1.5.

I have a date string of the form '2009/05/13 19:19:30 -0400'. It seems that previous versions of Python may have supported a %z format tag in strptime for the trailing timezone specification, but 2.6.x seems to have removed that.

What's the right way to parse this string into a datetime object?

解决方案

You can use the parse function from dateutil:

>>> from dateutil.parser import parse
>>> d = parse('2009/05/13 19:19:30 -0400')
>>> d
datetime.datetime(2009, 5, 13, 19, 19, 30, tzinfo=tzoffset(None, -14400))

This way you obtain a datetime object you can then use.

As answered, dateutil2.0 is written for Python 3.0 and does not work with Python 2.x. For Python 2.x dateutil1.5 needs to be used.

这篇关于如何在 Python 中使用 -0400 时区字符串解析日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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