17

I have read an array of strings from a TXT file and saved it as an array (of over thousand values) using such a line:

dates = np.genfromtxt('filename.txt', delimiter=";", usecols=(0), dtype=None)

Next, I would like to convert strings into dates. I tried to use the line:

dates2 = dt.datetime.strptime([dates], '"%Y-%m-%d"').date()

however, I got an error:

TypeError: must be string, not list

I figured out that such a code works fine:

data1='"2010-02-28"'
data1_1 = dt.datetime.strptime(data1, '"%Y-%m-%d"').date()

How should I deal with the described problem?

2 Answers 2

35

dates is a list of strings. So if you want to create a list of dates from its elements:

dates_list = [dt.datetime.strptime(date, '"%Y-%m-%d"').date() for date in dates]

This line iterates over the strings in the dates list and using list comprehension to create a new list of dates.

Note: '"%Y-%m-%d"' is not a mistake. OP's dates are surrounded by quotes.

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

6 Comments

I'm using Python 3.7.3 and I needed to remove the double quotes in order for this to work for me.
@MichaelSzczepaniak that's because your date strings are not surrounded with double-quotes like OP's.
@DeepSpace OP stands for ? to make this work I had to remove double-quotes "
@AnujGupta Original Poster, ie the quesion asker
@Confounded the datetime module, which is canonically imported as import datetime as dt
|
1

You can use split for faster result:

from datetime import datetime
today = datetime.now().strftime("%Y-%m-%d").split('-')

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.