Check if a string contains date or timestamp in python

datetime, python

Solution

you can match using a regex:

>>> 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.
>>> 

Play with it

The trick here, is to catch groups left and right of the `T` character, and paste them again around a space. As a bonus, if there's no match, there's no substitution.

Problem

I need to come up with a function which will take a single string and it will do the following : - check if it is a timestamp in UTC format (e.g. if it is of the form `2014-05-10T12:30:00`). - If it is in the format described above, replace 'T' with space and return the string. - If it is not of timestamp, simply return the string. What is the best way to accomplish this in python? I thought I could use datetime module. But can this be done using re module?

Original source