我使用的药剂1.8.0和3.0.7外生
我有地图的列表,看起来像这样
things = [
%{
availability_zone: "us-west-1a",
dns_name: "ec2-13-45-67-46.us-west-1.compute.amazonaws.com",
image_id: "ami-251234",
instance_id: "i-1234",
instance_state: "running",
instance_type: "m4.large",
ip_address: "13.45.67.46",
key_name: "some_key",
launch_time: "2018-06-13T16:34:04.000Z",
monitoring: "disabled",
private_ip_address: "10.1.1.1",
vpc_id: "vpc-9999"
},
%{
availability_zone: "us-west-1a",
dns_name: "ec2-13-99-99-46.us-west-1.compute.amazonaws.com",
image_id: "ami-2522344",
instance_id: "i-99999",
instance_state: "running",
instance_type: "m4.large",
ip_address: "13.99.99.99",
key_name: "some_key",
launch_time: "2018-06-13T16:34:04.000Z",
monitoring: "disabled",
private_ip_address: "10.1.1.2",
vpc_id: "vpc-9999"
}
]
我试图插入此列表到我的数据库使用Ecto.Repo.insert_all
。这并不是因为是工作,因为我打电话launch_time
一个utc_datetime
,这是不是在我的列表中的日期时间。
我试图将其转换为DateTime,然而,from_iso8601
返回一个元组,其中,当然,不能正常工作。
iex(12)> things |> Enum.map(fn elem ->
...(12)> Map.update!(elem, :launch_time, &DateTime.from_iso8601/1)
...(12)> end)
[
%{
availability_zone: "us-west-1a",
dns_name: "ec2-13-56-179-46.us-west-1.compute.amazonaws.com",
image_id: "ami-25110f45",
instance_id: "i-0df401bc2d3b16d37",
instance_state: "running",
instance_type: "m4.large",
ip_address: "13.56.179.46",
key_name: "salt_provisioning",
launch_time: {:ok, #DateTime<2018-06-13 16:34:04.000Z>, 0},
monitoring: "disabled",
private_ip_address: "10.81.1.244",
vpc_id: "vpc-07a5e160"
},
%{
availability_zone: "us-west-1a",
dns_name: "ec2-13-56-179-46.us-west-1.compute.amazonaws.com",
image_id: "ami-25110f45",
instance_id: "i-0df401bc2d3b16d37",
instance_state: "running",
instance_type: "m4.large",
ip_address: "13.56.179.46",
key_name: "salt_provisioning",
launch_time: {:ok, #DateTime<2018-06-13 16:34:04.000Z>, 0},
monitoring: "disabled",
private_ip_address: "10.81.1.244",
vpc_id: "vpc-07a5e160"
}
]
我怎样才能得到公正的日期时间回到我管,这样我可以insert_all
我的名单?或者,这是否需要多个步骤?
您现有的代码可以做一个小的变化工作,希望它符合您的要求:
things |> Enum.map(fn elem ->
{:ok, datetime, _} = DateTime.from_iso8601(elem[:launch_time])
Map.put(elem, :launch_time, datetime)
end)
虽然一个肯定会Enum.map/2
,惯用和更灵活的方式是使用Access
行为(Access.all/0
的列表)和Kernel.get_and_update_in/3
:
get_and_update_in(things, [Access.all(), :launch_time], fn prev ->
{prev, with {:ok, neu, _} <- DateTime.from_iso8601(prev), do: neu}
end)
(或(prev |> DateTime.from_iso8601() |> elem(1))
)如果所有的输入数据被证明是有效的。