I want to convert a list of datetime objects into strings, but am confused on how to accomplish this task.
hm=dt.date(2013,1,2)
t=hm.strftime('%m/%d/%Y')
t
This produces : '01/02/2013'
However, when I change up the variable to be a list of dates as so, it throws off an error.
hm=[dt.date(2013,1,1), dt.date(2013,1,2)]
t=hm.strftime('%m/%d/%Y')
t
Error: list indices must be integers or slices, not datetime.date
Do I need to use some sort of for loop to accomplish this task?
You need to iterate over the list to convert each individual date into a string:
>>> t = [d.strftime('%m/%d/%Y') for d in hm]
Or if you want a string with all dates converted to a string concatenated by some other string (let's say ,) you can also do as:
>>> s = ', '.join(t)
If you want to solve this problem with a "conventional" for loop you can use:
import datetime as dt
hm = [dt.date(2013, 1, 1), dt.date(2013, 1, 2)]
t = []
for date in hm:
t.append(date.strftime('%m/%d/%Y'))
Otherwise the answer posted by dcg would be a cleaner and much better method.
Related
I have a variable which is a = '"[200.0', ' 100.0]"'. While trying to access individual element like a[0] = '"[200.0'
The data type of this I checked says tuple. This is not the format I can work on, hence I want to convert this to a simple list/array like the following format for ex:
a = [200.0,100.0] .So that a[0] = 200.0 which could be either float or int data type.
I have tried using literal_eval, eval but it keeps throwing an error. A workable solution would be really helpful. Any ideas for this?
You can do it with regex to clean the a string from unwanted characters and then split it by the , to be a list
import re
a = '"[200.0', ' 100.0]"'
a = [re.sub(r"""["'\[\] ]""", "",i) for i in a]
print(a)
Output
['200.0', '100.0']
OR if you want it to be from float type
a = [float(re.sub(r"""["'\[\] ]""", "",i)) for i in a]
print(a)
Output
[200.0, 100.0]
Just for fun, you could also try this:
my_list = eval(eval(",".join(a)))
Explanation:
",".join(a) produces a single string '"[200.0, 100.0]"'
Calling eval() on this strips away the outer single-quotes, producing "[200.0, 100.0]" (that's a string containing [ as the first character and ] as the last)
Calling eval() again on this evaluates the above string, producing [200.0, 100.0], which gets assigned to my_list as a proper list object
I know that we can create a single string to np.datetime64 format such as:
a = np.datetime64('2020-01-01')
But what if we have a list with multiple strings of dates in it?
How are we able to apply the same np.datetime64 to convert all the elements inside into a datetime format? Apart from doing a for-loop perhaps.
When you have your string list, use it as a source to a Numpy array,
passing datetime64 as dtype. E.g.:
lst = ['2020-01-01', '2020-02-05', '2020-03-07' ]
a = np.array(lst, dtype='datetime64')
When you execute a (actually print this array in a notebook),
you will get:
array(['2020-01-01', '2020-02-05', '2020-03-07'], dtype='datetime64[D]')
As you can see, in this case the default precision is Day.
But you can pass the precision explicitely, e.g. b = np.array(lst, dtype='datetime64[s]').
Don't be misled by apostrophes surrounding each element in the above
printout, they are not strings. To check it, execute a[0] and
you will get:
numpy.datetime64('2020-01-01')
Using list comprehension:
strings_list= [...]
npdate_list = [np.datetime64(x) for x in strings_list]
Is there a specific reason for you to want to avoid a loop?
List comprehension is okay?
I got a list of values and i would like to convert it in an array in order to extract easily columns, but i m embarassed with " which doesn t allow to use : " x = np.array(a, dtype=float)"
['"442116.503118","442116.251106"',
'"442141.502863","442141.247462"',
...
The message obtained is :
"could not convert string to float: "442116.503118","442116.251106""
Answering based on the VERY limited information given, but if that is your list it looks like a list of nested strings, not floats. Try
x = np.array([float(i.replace("\"","")) for i in a], dtype=float)"
This is just wrong... This does the trick for me though:
import numpy as np
wtf = ['"442116.503118","442116.251106"',
'"442141.502863","442141.247462"']
to_list = []
for nest1 in wtf:
nest2 = nest1.split(',')
for each in nest2:
to_list.append(float(each.strip('"')))
to_array = np.asarray(to_list)
Not exactly elegant. You need to deal with each level of nesting in your input data. I'd recommend you reconsider the way you're formatting the data you're inputting.
I have a list of tuples:
lst = [('Q4-2005', 327.93), ('Q1-2005', 133.05), ('Q3-2005', 500.95), ('Q2-2005', 254.22)]
I want to sort this list by the first element of each tuple. Thus my resulting, sorted list should look like:
[('Q1-2005', 133.05), ('Q2-2005', 254.22), ('Q3-2005', 500.95), ('Q4-2005', 327.93)]
I tried doing this using sorting() and lambda, but the resulting list is not sorted. Im thinking its because my 'dates' are actually strings:
sorted(lst, key = lambda x: x[0])
So i guess I have 2 questions..
First, How do I sort the list of tuples so that they are in chronological order?
Second, what is the best way to make python realize that 'Q1-2005' is a date? Eventually I want to plot this data where x-axis is the 'date' and y-axis is the number associated with each date?
You said that you want Python to interpret Q1-2005 as a date. If you convert the list to such a format, then sorting becomes trivial, and plotting will also be easier. Here's one way to do it using datetime.date (it encodes the quarters as a date representing the first date of the quarter).
from datetime import date
# date() takes in year, month, day args
date_lst = [(date(int(q[3:]), 3 * int(q[1]) - 2, 1), v)
for q, v in lst]
This will result in something like this:
[(datetime.date(2005, 10, 1), 327.93),
(datetime.date(2005, 1, 1), 133.05),
(datetime.date(2005, 7, 1), 500.95),
(datetime.date(2005, 4, 1), 254.22)]
After that, sorting chronologically is as simple as sorted(date_lst).
The best way to do this, redefining a sort, would be to make a new class or a new function. The default sort algorithms in Python use traditional lexicographical sorting. Calling sort(tuple) will sort them in alphabetical/alphanumeric order, but not necessarily the order you want.
I will note, sorting by default will sort the tuples based on their index [0] value, only going to index [1] if two first indices are the same.
dont name your variable list!!!
sorted(the_list, key=lambda x: list(reversed(map(int,x[0][1:].split("-")))))
Using an object with __lt__ and/or __cmp__ would be good, but if you want to use a key function:
#!/usr/local/cpython-3.3/bin/python
list_ = [('Q4-2005', 327.93), ('Q1-2005', 133.05), ('Q3-2005', 500.95), ('Q2-2005', 254.22), ('Q1-2006', 123.45), ('Q2-2007', 678.90), ]
def key(element):
subresult1 = element[0]
subresult2 = subresult1.split('-')
subresult2.reverse()
subresult2[0] = int(subresult2[0])
return subresult2
list_.sort(key=key)
print(list_)
Which out for the years - they're more significant than the quarters.
I have the following string:
(1, 2, 3, 4)
I want to convert it to just the last two values:
(3, 4)
In my actual code all four fields are whole numbers but vary greatly in length. I've tried doing this with both regex and 'for' statements as well as trying the various answers to similar questions here on SO but so far no luck.
This gives you the last two terms in your tuple:
>> a = (1,2,3,4)
>> a[-2:]
(3,4)
It sounds like you want to use the slice operator.
Edit: Perhaps this is a better link. Scroll down a bit for the slice notation stuff. The examples deal with strings, but it should work with any sequence type.
If (1,2,3,4) is tuple:
data = (1,2,3,4)
newData = data[-2:]
If you have '(1,2,3,4)' then:
import ast
data = ast.literal_eval('(1,2,3,5)')
newData = data[-2:]
Or in case you have to split such list in a certain value:
def get_slice(inputData, searchVal):
if searchVal in inputData and inputData.index(searchVal) < len(inputData):
return inputData[inputData.index(searchVal)+1:]
return ()
get_slice((1,2,3,4),2)