MEhsan MEhsan - 4 months ago 8
Python Question

How to Remove the Timestamp in a File?

I have the following data:

DOBirth
2/17/1937 00:00:00:00
3/2/1941 00:00:00
8/9/1928 00:00
1/1/1971 0:00
9/3/1963 :00


What is the appropriate way that I can use to remove the extraneous zeros after the birth column?

The output should be like:

DOBirth
2/17/1937
3/2/1941
8/9/1928
1/1/1971
9/3/1963

Answer

Simply split by space and return the first item:

>>> s = """DOBirth
... 2/17/1937 00:00:00:00
... 3/2/1941 00:00:00
... 8/9/1928 00:00
... 1/1/1971 0:00
... 9/3/1963 :00"""
>>> for line in s.splitlines():
...     print(line.split(" ", 1)[0])
... 
DOBirth
2/17/1937
3/2/1941
8/9/1928
1/1/1971
9/3/1963

where 1 in line.split(" ", 1) is the maxsplit value - splitting by the first space only, since it is not relevant for us what comes after.