alexa

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

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

203 0
7

Write a Comments


* Be the first to Make Comment

GoodFirms Badge
GoodFirms Badge

Fix Your Meeting With Our SEO Consultants in India To Grow Your Business Online

Facebook
Twitter
LinkedIn
Instagram
Whatsapp
Call Now
Quick Inquiry