Python:如何将字符串转换为日期时间 [英] Python: How to convert string into datetime

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

问题描述


可能重复:

将字符串转换为日期时间

我正在解析一个XML文件,该文件我的时间分别是同种格式:

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

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

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

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?

谢谢。

推荐答案

使用 datetime .strptime 方法:

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

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

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

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

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