datetime strptime-设置格式以忽略字符串的结尾部分 [英] datetime strptime - set format to ignore trailing part of string
问题描述
我有一个长度可变的字符串,并且我想给strptime
一种格式,以便忽略字符串的其余部分.让我举例说明.我有类似的东西
I have a string with variable length and I want to give a format to strptime
in order for the rest of the string to be ignored. Let me exemplify. I have something like
9/4/2013,00:00:00,7.8,7.4,9.53
10/4/2013,00:00:00,8.64,7.4,9.53
,我想要一种使命令strptime(line,format)
能够读取这些行的格式.类似format='%d/%m/%Y,%H:%M:%S*'
的东西,尽管我知道这不起作用.我想我的问题有点类似于这个问题,但是那里没有答案可以帮助我,我的问题会更糟,因为我的琴弦的全长可能会有所不同.我感觉dateutil
可以解决我的问题,但是我找不到能解决问题的东西.
and I want a format that makes the command strptime(line,format)
work to read those lines. Something like format='%d/%m/%Y,%H:%M:%S*'
, although I know that doesn't work. I guess my question is kind of similar to this one, but no answer there could help me and my problem is a little worse because the full length of my string can vary. I have a feeling that dateutil
could solve my problem, but I can't find something there that does the trick.
我可能可以做类似strptime(''.join(line.split(',')[:2]),format)
的操作,但是我不想在与用户相关的问题上诉诸于此.
I can probably do something like strptime(''.join(line.split(',')[:2]),format)
, but I wouldn't want to resort to that for user-related issues.
推荐答案
您不能让datetime.strptime()
忽略部分输入.您的 only 选项实际上是先分割掉多余的文本.
You cannot have datetime.strptime()
ignore part of the input.; your only option really is to split off the extra text first.
是的,您要做必须拆分并重新加入您的字符串:
So yes, you do have to split and rejoin your string:
format = '%d/%m/%Y,%H:%M:%S'
datetime.strptime(','.join(line.split(',', 2)[:2]), format)
或找到其他方法来提取信息.您可以使用正则表达式,例如:
or find some other means to extract the information. You could use a regular expression, for example:
datetime_pattern = re.compile(r'(\d{1,2}/\d{1,2}/\d{4},\d{2}:\d{2}:\d{2})')
format = '%d/%m/%Y,%H:%M:%S'
datetime.strptime(datetime_pattern.search(line).group(), format)
这篇关于datetime strptime-设置格式以忽略字符串的结尾部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!