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

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

问题描述

我收到一个像2009-05-28T16:15:00这样的格式的datetime字符串(这是ISO 8601,我相信)一个hack-ish选项似乎是使用<$ c解析字符串$ c> time.strptime 并将touple的前6个元素传递到datetime构造函数中,如:

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

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

我没有找到一个更干净的方法,是吗? p>

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 datetime字符串转换为Python datetime对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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