Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - converting strings in an array to dates

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?

like image 421
kaksat Avatar asked May 27 '15 16:05

kaksat


2 Answers

Note to future readers: Please do not edit this answer. '"%Y-%m-%d"' is not a mistake. OP's dates are surrounded by quotes.


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.

like image 151
DeepSpace Avatar answered Sep 18 '22 06:09

DeepSpace


You can use split for faster result:

from datetime import datetime
today = datetime.now().strftime("%Y-%m-%d").split('-')
like image 32
PouriaDiesel Avatar answered Sep 21 '22 06:09

PouriaDiesel