2015-07-22 61 views
1

我试图从CSV文件日期并将其转换为划时代的时间错误使用strptime,而strftime的转换日期划时代

CSV.foreach(File.path("month.csv")) do |row| 
dateper=row[0].split(',')[0] 
p DateTime.strptime(dateper,"%m/%d/%y %I:%M:%S %p %z").strftime("%s") 
end 

我越来越无效日期(引发ArgumentError)作为结果。但是,如果我打印出dateper,请随机选择一个输出,并在第3行将其粘贴到dateper的位置,我会得到一个纪元值。我究竟做错了什么? dateper是字符串值,strptime减去strftime似乎给出了一个输出。

month.csv样品:

13年7月26日上午12点00分00秒-05:00,62.2,63.02,62.07,63.02,5.00168E + 07
13年8月23日12: 00:00 AM -05:00,71.84,71.93,71.36,71.6,5.55304E + 07
8/26/13 12:00:00 AM -05:00,71.56,72.91,71.52,71.87,8.26536E + 07
13年8月27日12:00:00 AM -05:00,71.16,71.81,69.49,69.82,1.058488E + 08

有人能帮助我吗?

+1

你能给你的CSV几行?理想情况下,您发现的行不起作用? – Amadan

+0

在你的'dateper = ...'声明后面加上'puts dateper',看它是否与你认为它应该是相符的。 – Beartech

+0

@Amadan: 一行CSV有 13年7月26日12:00:00 AM -05:00,62.2,63.02,62.07,63.02,5.00168E + 07 更多的行会看起来像 8/23/13 12:00:00 AM -05:00,71.84,71.93,71.36,71.6,5.55304E + 07 8/26/13 12:00:00 AM -05:00,71.56,72.91,71.52,71.87, 8.26536E + 07 8/27/13 12:00:00 AM -05:00,71.16,71.81,69.49,69.82,1.058488E + 08 – mantrarush

回答

0

你的某个地方有一些畸形的日期。使用rescue可避免脚本窒息。

CSV.foreach(File.path("month.csv")) do |row| 
dateper=row[0].split(',')[0] 
p DateTime.strptime(dateper,"%m/%d/%y %I:%M:%S %p %z").strftime("%s") rescue p "malformed date:#{dateper} on line #{$.}" 
end 

这将允许脚本继续并显示不良日期。

+0

感谢您的意见,这有帮助:) – mantrarush

+0

随时接受上面的答案。 :-) – Beartech