2015-07-22 59 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