如何将 ISO 8601 日期时间字符串转换为 Python 日期时间对象? [英] How do I translate an ISO 8601 datetime string into a Python datetime object?

查看:83
本文介绍了如何将 ISO 8601 日期时间字符串转换为 Python 日期时间对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到的日期时间字符串的格式类似于2009-05-28T16:15:00"(我相信这是 ISO 8601).一个hackish选项似乎是使用 time.strptime 解析字符串并将元组的前六个元素传递给 datetime 构造函数,例如:

I'm getting a datetime string in a format like "2009-05-28T16:15:00" (this is ISO 8601, I believe). One hackish option seems to be to parse the string using time.strptime and passing the first six elements of the tuple into the datetime constructor, like:

datetime.datetime(*time.strptime("2007-03-04T21:08:12", "%Y-%m-%dT%H:%M:%S")[:6])

我一直无法找到一种更干净"的方法来做到这一点.有吗?

I haven't been able to find a "cleaner" way of doing this. Is there one?

推荐答案

我更喜欢使用 dateutil 用于时区处理和一般可靠日期解析的库.如果你得到一个 ISO 8601 字符串,如:2010-05-08T23:41:54.000Z 你会很高兴用 strptime 解析它,特别是如果你不知道是否包含时区.pyiso8601 有几个问题(检查他们的跟踪器),我在使用过程中遇到了这些问题,并且已经有几年没有更新了.相比之下,dateutil 一直很活跃并为我工作:

I prefer using the dateutil library for timezone handling and generally solid date parsing. If you were to get an ISO 8601 string like: 2010-05-08T23:41:54.000Z you'd have a fun time parsing that with strptime, especially if you didn't know up front whether or not the timezone was included. pyiso8601 has a couple of issues (check their tracker) that I ran into during my usage and it hasn't been updated in a few years. dateutil, by contrast, has been active and worked for me:

from dateutil import parser
yourdate = parser.parse(datestring)

这篇关于如何将 ISO 8601 日期时间字符串转换为 Python 日期时间对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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