Python:如何将字符串转换为日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12672629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:34:18  来源:igfitidea点击:

Python: How to convert string into datetime

pythondatetime

提问by Sunny

Possible Duplicate:
Converting string into datetime

可能的重复:
将字符串转换为日期时间

I am parsing an XML file that gives me the time in the respective isoformat:

我正在解析一个 XML 文件,该文件为我提供了相应 isoformat 的时间:

tc1 = 2012-09-28T16:41:12.9976565
tc2 = 2012-09-28T23:57:44.6636597

But it is being treated as a string when I retrieve this from the XML file. I have two such time values and i need to do a diff between the two so as to find delta. But since it is a string I can not directly do tc2-tc1. But since they are already in isoformat for datetime, how do i get python to recognize it as datetime?

但是当我从 XML 文件中检索它时,它被视为一个字符串。我有两个这样的时间值,我需要在两者之间做一个差异以找到增量。但由于它是一个字符串我不能直接做 tc2-tc1。但是由于它们已经是日期时间的isoformat,我如何让python将其识别为日期时间?

thanks.

谢谢。

采纳答案by Pierre GM

Use the datetime.strptimemethod:

使用datetime.strptime方法:

import datetime
datetime.datetime.strptime(your_string, "%Y-%m-%dT%H:%M:%S.%f")

The link provided presents the different format directives. Note that the microseconds are limited to the range [0,999999], meaning that a ValueErrorwill be raised with your example (you're using 1/10us): you need to truncate your string to drop the final character.

提供的链接显示了不同的格式指令。请注意,微秒仅限于 range [0,999999],这意味着 aValueError将在您的示例中引发(您使用的是 1/10us):您需要截断字符串以删除最后一个字符。

回答by Sunny

Use the datetimemodule.

使用datetime模块

td = datetime.strptime('2012-09-28T16:41:12.997656', '%Y-%m-%dT%H:%M:%S.%f') - 
     datetime.strptime('2012-09-28T23:57:44.663659', '%Y-%m-%dT%H:%M:%S.%f')
print td
# => datetime.timedelta(-1, 60208, 333997)

There is only one small problem: Your microseconds are one digit to long for %fto handle. So I've removed the last digits from your input strings.

只有一个小问题:你的微秒是一位%f需要处理的数字。所以我从你的输入字符串中删除了最后一位数字。

回答by Antonio Beamud

You can use the python-dateutil parse()function, it's more flexible than strptime. Hope this help you.

您可以使用python-dateutilparse()函数,它比 strptime 更灵活。希望这对你有帮助。