converting dates and times with list comprehension

I have a whole bunch of data and there are two lists consisting of dates and times that look as such:

dates: year-month-day

times: hour:minute:second

so I take them appart and put each into a separate list:

year,month,day = [i.split("-")[0] for i in date], [i.split("-")[1] for i in date], [i.split("-")[2] for i in date]
hour,minute,second = [i.split(":")[0] for i in time], [i.split(":")[1] for i in time], [i.split(":")[2] for i in time]

now I since each of these are long lists of the same length, I want to convert them into one list that contains them as datetime objects. So I used another list comprehension for this:

datetime_column = [datetime.datetime(int(y),int(m),int(d),int(h),int(m),int(s)) for y,m,d,h,m,s in year,month,day,hour,minute,second]

this gives me the following error:

ValueError: too many values to unpack

I know that this is because it is trying to iterate y,m,d,h,m and s through each list rather than just pair them up such as y with year, m with month, and so on. So here is my question:

How can you use list comprehension with 6 variables each going through 1 of 6 separate lists? And if it is not possible, what would be an efficient way to do the equivalent?

Answers


You are making things too complicated for yourself. Zip the date and time lists, then use datetime.datetime.strptime():

datetime_column = [datetime.datetime.strptime('{} {}'.format(d, t),
                                              '%Y-%m-%d %H:%M:%S')
                   for d, t in zip(date, time)]

zip() pairs up each date string with each time string, then we use each pair to create a full timestamp string, to be parsed by the strptime() method.


Need Your Help

iOS : Slow searching in SQLite database

iphone objective-c ios xcode ipad

I have created a dictionary app with SQL data base , but the problem is when users search a word in UISearchBar the searching process is very slow ! why this happens ? here is my code :

set_union issue while using arrays

c++ stl set-union

I am trying to get union of 4 arrays using set_union. Here is the code I have so far: