简体   繁体   English

将xsd:dateTime格式的字符串解析为python datetime

[英]Parse xsd:dateTime formatted string to python datetime

Given a string in xsd:dateTime format I want to create a python datetime object. 给定xsd:dateTime格式的字符串,我想创建一个python datetime对象。 I especially need to be able to parse for example a string like this '2012-09-23T09:55:00', but also all other defined examples should be parsed correctly, and also use timezones. 我特别需要能够解析这样的字符串,例如'2012-09-23T09:55:00',而且所有其他定义的示例也应正确解析,并使用时区。

Use the datetime.datetime.strptime class method to parse these: 使用datetime.datetime.strptime类方法可以解析以下内容:

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

Your example does not include a timezone however. 您的例子包括时区但是。 If you really do need timezone support, best resort to the python-dateutil module : 如果您确实需要时区支持,则最好使用python-dateutil模块

from dateutil.parser import parse
dt = parse(xsdDateTime)

i would also recommend the python-dateutil package. 我也推荐python-dateutil包。 i am using version 2.7.3, that also has an isoparser. 我正在使用2.7.3版本,该版本也具有isoparser。 however, the isoparser doesn't parse time only strings, and i've filled an issue. 但是,isoparser不会仅分析时间字符串,而我填补了一个问题。 use the parser module instead. 请改用解析器模块。

from dateutil.parser import parse
dt = parse(xsdDateTime)

hth, alex 亚历克斯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM