FlyUFalcon
FlyUFalcon

Reputation: 344

Format and Sort date and time in Python

I imported csv file to Python and it looks like

ric       date           time       price
VOD   01-AUG-2013     8:08:53.241    156
VOD   03-JAN-2013     8:25:43.241    129
VOD   07-MAR-2013     8:03:31.241    128
VOD   18-AUG-2013     8:18:53.241    120
...     ...              ...         ...

I need to sort this file by date and then by time from the oldest to newest. However, I have to format the date and time first. But I am not sure how to do that. I tired to format date first, but it did work out.

My code is:

import pandas as pd
import time
import datetime
from datetime import datetime

path = 'C:\\sample.csv'

data= pd.read_csv(path)
sorted(data, key=lambda each_dict: datetime.strptime(each_dict['date'], '%d-%b-%y'))

Can someone help me to format and sort date and time ? thanks !

Upvotes: 1

Views: 5455

Answers (2)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210862

try pandas, you'll love it:

from __future__ import print_function

import pandas as pd

df = pd.read_csv('data.csv', delimiter=r'\s+')
df['date'] = pd.to_datetime(df['date'] + ' ' + df['time'])
del df['time']
print(df.sort(['date'], ascending=[0]).to_string(index=False))

Output:

 ric                    date  price
 VOD 2013-08-18 08:18:53.241    120
 VOD 2013-08-01 08:08:53.241    156
 VOD 2013-03-07 08:03:31.241    128
 VOD 2013-01-03 08:25:43.241    129

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107297

You can use following formats for converting your dates and times to datetime object:

For time:

'%H:%M:%S.%f'

For date:

'%d-%b-%Y'

And use a tuple which its first item is date and second is time :

sorted(data,
       key=lambda each_dict: (datetime.strptime(each_dict['date'], '%d-%b-%Y'),
                              datetime.strptime(each_dict['time'], '%H:%M:%S.%f'))

Upvotes: 1

Related Questions