Advertisement

TrimwebsolutionsTrimwebsolutions

Problem and Solutions

Transform spaced dates in CSV file to datetime with in python ?

By M.K. Verma · 3 May 2022

Transform spaced dates in CSV file to datetime with in python ?

Use strptime from the datetime  library.

from datetime import datetime
with open("dates.txt", 'r') as f:
    dates = []
    for event in f.readlines()[1:]
        # " ".join(event.split()[:5]) will extract the first 5 columns
        date = datetime.strptime(" ".join(event.split()[:5]), "%Y %m %d %H %M")
        dates.append(date)

or shorter by using list comprehension

from datetime import datetime
with open("dates.txt", 'r') as f:
    dates = [datetime.strptime(" ".join(event.split()[:5]), "%Y %m %d %H %M") for event in f.readlines()[1:]]

To make the list into a Pandas dataframe you can do df = pd.DataFrame({'Events': dates}) after having imported pandas.

               Events
0 2008-01-02 04:42:00
1 2008-01-02 04:51:00
2 2008-01-02 04:56:00
3 2008-01-02 06:16:00
4 2008-01-09 15:05:00