我在迁移中指定什么数据类型才能使用 FasterCSV 从 CSV 导入日期?

发布于 2024-12-19 10:03:17 字数 278 浏览 4 评论 0原文

各位溢出者,

我有一个制表符分隔的 csv 文件,其中包含以下格式的日期: 30-11-2011 2:24

我正在使用 FasterSCV gem 解析 csv。我创建了一个迁移,将此信息存储为日期时间。我应该这样做还是将其定义为 string 并让 Ruby 每次检索它时都将其转换?

我是否需要定义一些 FasterCSV 转换器?

谢谢...

Fellow Overflowers,

I have a tab delimited csv file which contains dates in this format:
30-11-2011 2:24

I am parsing the csv with FasterSCV gem. I have created a migration which stores this info as datetime. Should I be doing that or define it as string and let Ruby convert it each time i retrieve it?

Do I need maybe to define some FasterCSV converters?

Thanks...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

人间不值得 2024-12-26 10:03:17

日期时间有点棘手。是有严格的格式

irb(main):008:0> DateTime.now
=> Fri, 02 Dec 2011 22:14:57 +0100

但你可以这样做

irb(main):015:0> t = DateTime.parse("30-11-2011 2:24").utc
=> Wed, 30 Nov 2011 02:24:00 +0000
irb(main):016:0> t.class
=> DateTime

现在你有一个 DateTime 对象。但是,请注意解析方法末尾的时区

当您填充数据库时,请使用 db 文件夹中的 seeds.rb 文件。
我通常在 db 文件夹中创建一个文本文件,使用我的编辑器并用“|”替换所有选项卡并为每一行创建一个数组
假设它看起来像这样(假设它是一个待办事项列表)

待办事项文件

make hay|30-11-2011 2:24
fix tractor|24-11-2011 2:14

seeds.rb 文件

open("db/todo") do |todos|
  todos.read.each_line do |todo|
    n = todo.chomp.split("|")
    Todo.create!(:entry => n[0], :at_date => DateTime.parse("#{n[1]}").utc)
  end
end

,然后运行

rake db:seed

​​Make a some ruby​​ magic!
我还没有测试过这段代码,但它可能会推动你走向正确的方向

DateTime is a bit tricky. Is has a strict format

irb(main):008:0> DateTime.now
=> Fri, 02 Dec 2011 22:14:57 +0100

But you can do this

irb(main):015:0> t = DateTime.parse("30-11-2011 2:24").utc
=> Wed, 30 Nov 2011 02:24:00 +0000
irb(main):016:0> t.class
=> DateTime

Now you have a DateTime object. But, pay attention to the time zone at the end of the parse method

When you fill the database use the seeds.rb file in your db folder.
I usually make a text file in the db folder, use my editor and replace all tabs with a "|" and make an array of each line
Lets say it looks like this (asuming it is a todo list)

todo file

make hay|30-11-2011 2:24
fix tractor|24-11-2011 2:14

seeds.rb file

open("db/todo") do |todos|
  todos.read.each_line do |todo|
    n = todo.chomp.split("|")
    Todo.create!(:entry => n[0], :at_date => DateTime.parse("#{n[1]}").utc)
  end
end

then run

rake db:seed

Make a some ruby magic!
I have not tested this code, but it might push you in the right direction

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文