1

I have an column in excel which has dates in the format ''17-12-2015 19:35". How can I extract the first 2 digits as integers and append it to a list? In this case I need to extract 17 and append it to a list. Can it be done using pandas also?

Code thus far:

import pandas as pd
Location = r'F:\Analytics Materials\files\paymenttransactions.csv'
df = pd.read_csv(Location)
time = df['Creation Date'].tolist()
print (time)
5
  • 3
    Please provide code that shows what you have tried so far. Commented Jan 6, 2016 at 22:28
  • import pandas as pd Location = r'F:\Analytics Materials\files\paymenttransactions.csv' df = pd.read_csv(Location) time = df['Creation Date'].tolist() print (time) I have been able to take the column and convert that into the list. A small portion of the list is as below. ['11/12/2015 18:59', '22/12/2015 07:42', '17/12/2015 22:44', '28/12/2015 22:50', '17/12/2015 19:35', '5/12/2015 18:46', '8/12/2015 20:28', '8/12/2015 0:36', '27/12/2015 17:57', '10/12/2015 12:19', '10/12/2015 12:16' Commented Jan 6, 2016 at 22:34
  • You can always edit your question. It'd be a lot nicer if you could add that example to the actual question instead. Code in comments is quite unreadable as you can see. Commented Jan 6, 2016 at 22:37
  • python-excel.org Commented Jan 6, 2016 at 22:42
  • Apologies for the inconvenience.I have pasted the code in the questions now. Commented Jan 6, 2016 at 22:42

1 Answer 1

1

You could extract the day of each timestamp like

from datetime import datetime
import pandas as pd

location = r'F:\Analytics Materials\files\paymenttransactions.csv'
df = pd.read_csv(location)

timestamps = df['Creation Date'].tolist()
dates = [datetime.strptime(timestamp, '%d-%m-%Y %H:%M') for timestamp in timestamps]
days = [date.strftime('%d') for date in dates]

print(days)

The '%d-%m-%Y %H:%M'and '%d' bits are format specififers, that describe how your timestamp is formatted. See e.g. here for a complete list of directives.

datetime.strptime parses a string into a datetimeobject using such a specifier. dateswill thus hold a list of datetime instances instead of strings.

datetime.strftime does the opposite: It turns a datetime object into string, again using a format specifier. %d simply instructs strftime to only output the day of a date.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.