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

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

问题描述

我正在获取日期时间字符串,其格式为 2009-05-28T16:15:00(我相信这是ISO 8601)。一种可能的选择似乎是使用 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:

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

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

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