I have a problem. I want to transform the date from '2008-09-24'
to '24.09.2008'
. What I got is <function <lambda> at 0x000001CD2B9CE820>
. How could I loop through the host_since
and transform the date?
host_since = npListings[:,4].astype(np.datetime64)
# host_since =
['2008-09-24' '2009-12-02' '2009-11-20' '2010-03-23' '2010-05-13'
'2010-05-13' '2010-05-25' '2010-07-23' '2009-12-22' '2010-08-08']
get_cubes = lambda x: [datetime.strptime(d, '%y-%m,%d').strftime('%d.%m.%Y') for d in range(host_since.shape[0])]
print(get_cubes)
[OUT]
<function <lambda> at 0x000001CD2B9CE82
What I want is get_cubes = ['24.09.2008' ... '08.08.2010'] # should be also a numpy array
CodePudding user response:
2 points:
- Looking at the dates you include as an example, in the
strptime
function you have the wrong format, which should be%Y-%m-%d
and not%y-%m,%d
for d in range(host_since.shape[0])
iterates integer numbers, right? So how does thestrptime
work then?- We are clearly starting from the assumption that all the string dates are in the correct parseable format - note that, if that is not the case, a
ValueError
will the thrown bystrptime
, so maybe some sanity check is needed as well.
I have rewritten your code as follows:
host_since =np.array(\
['2008-09-24', '2009-12-02', '2009-11-20', '2010-03-23', '2010-05-13',
'2010-05-13', '2010-05-25', '2010-07-23', '2009-12-22', '2010-08-08'])
cubes = [datetime.strptime(d, '%Y-%m-%d').strftime('%d.%m.%Y') for d in host_since]
print(cubes)
If your want to use range
, in my view you should write as follows:
cubes = [datetime.strptime(host_since[d], '%Y-%m-%d').strftime('%d.%m.%Y') for d in range(host_since.shape[0])]
print(cubes)
As stressed above, using a lambda function here is unnecessary.
CodePudding user response:
As @Reti43 mentioned, you might as well skip the lambda altogether.
cubes = [datetime.strptime(str(host_since[i]), '%Y-%m-%d').strftime('%d.%m.%Y')
for i in range(host_since.shape[0])]
print(cubes)
Note: If the data in your commented-out host_since
variable matches what's actually in your numpy array, you'll want to change your strptime
format to %Y-%m-%d
.