用Python解析时间戳 [英] Parsing Timestamp in Python
问题描述
我有一个应用程序,需要解析四种不同格式的时间戳。
I have an application in which I need to parse timestamps of four different formats.
HH:MM:SS
HH:MM:SS.mm
MM:SS
MM:SS.mm
如何编写将这些格式中的任何一种解析为 timedelta
对象的函数?
How can I write a function to parse any of these formats into a timedelta
object?
I当我看到:
时,尝试一个接一个地循环遍历字符和 break
,但是我的代码很混乱,所以我宁愿这里没有它作为基准。
I have tried iterating through the characters one by one and break
ing when I see the :
, but my code is a mess, so I would rather not have it here as a baseline.
推荐答案
这是使用 datetime.datetime.strptime()
:
如果您不提前知道哪个格式,然后输入,您可以尝试将所有输入换成 try
/ catch
块。
If you don't know ahead of time which format your input will be in, you can try all of them wrapped in a try
/catch
block.
strptime()
返回 datetime
对象,因此调用 .time()
函数仅获取时间部分。请参阅此帖子
strptime()
returns a datetime
object, so call the .time()
function to get only the time part. See this post for more details.
import datetime
def parse_timestamp(ts):
formats = [
"%H:%M:%S", #HH:MM:SS
"%H:%M:%S.%f", #HH:MM:SS.mm
"%M:%S", #MM:SS
"%M:%S.%f" #MM:SS.mm
]
for f in formats:
try:
return datetime.datetime.strptime(ts, f).time()
except ValueError:
pass
return None
示例:
timestamps = [
"12:34:56",
"12:34:56.78",
"34:56",
"34:56.78"
]
for ts in timestamps:
print parse_timestamp(ts)
输出:
12:34:56
12:34:56.780000
00:34:56
00:34:56.780000
或者如果您知道特定格式,则可以直接使用 datetime.datetime.strptime(ts,f).time()
。
Or if you know the specific format, you can use datetime.datetime.strptime(ts, f).time()
directly.
更新1
如果要转换为 timedelta
s,您可以使用 parse_timestamp()
和 timedelta
构造函数:
If you want to convert to timedelta
s, you can do so using the output of parse_timestamp()
and the timedelta
constructor:
def time_to_timedelta(t):
td = datetime.timedelta(
seconds=t.second,
microseconds=t.microsecond,
minutes=t.minute,
hours=t.hour
)
return td
这是与相关的帖子可能对您也有用。
Here is a related post that you may also find useful.
这篇关于用Python解析时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!