我需要提出一个函数,它将采用一个字符串,它将执行以下操作:
2014-05-10T12:30:00
)。在python中实现这一目标的最佳方法是什么?我以为我可以使用datetime模块。但这可以使用re模块完成吗?
答案 0 :(得分:3)
你可以使用正则表达式进行匹配:
>>> s1 = "1) check if it is a timestamp in UTC format (e.g. if it is of the form '2014-05-10T12:30:00')."
>>> s2 = "3) If it is not of timestamp, simply return the string."
>>> re.compile('\d\d\d\d-\d\d-\d\d\(T\)\d\d:\d\d:\d\d')
<_sre.SRE_Pattern object at 0x7f9781558470>
>>> s = re.sub(r'(.*\d\d\d\d-\d\d-\d\d)T(\d\d:\d\d:\d\d.*)',r'\1 \2',s1)
>>> print(s)
1) check if it is a timestamp in UTC format (e.g. if it is of the form '2014-05-10 12:30:00').
>>> s = re.sub(r'(.*\d\d\d\d-\d\d-\d\d)T(\d\d:\d\d:\d\d.*)',r'\1 \2',s2)
>>> print(s)
3) If it is not of timestamp, simply return the string.
>>>
这里的技巧是捕捉T
字符左右两侧的组,然后再将它们粘贴到一个空格周围。作为奖励,如果没有匹配,则没有替代。
答案 1 :(得分:3)
虽然zmo的答案是正确的,但我看到很多人,尤其是经验丰富的系统管理员,他们非常善于使用正则表达式选择经常制作他们自己的正则表达式。 正则表达式很难维护和阅读,而Python自己的STL提供了一些经过实践检验的方法,无需重新发明正确的正则表达式。 这是我的2分,Pythonic解决方案:
In[87]: import time
In[88]: correct = "2014-05-10T12:30:00"
In[89]: wrong = "some string" # will raise ValueError
In[90]: try:
time.strptime(correct, "%Y-%m-%dT%H:%M:%S")
correct = correct.replace('T',' ')
except ValueError:
pass
....
In [91]: correct
Out[91]: '2014-05-10 12:30:00'
In [93]: wrong = "foo bar baz"
In [94]: try:
time.strptime(wrong, "%Y-%m-%dT%H:%M:%S")
correct = correct.replace('T',' ')
except ValueError:
pass
....
In [95]: wrong
Out[95]: 'foo bar baz'