Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

ruby on rails - How would you convert a string in the wrong format to datetime

I am very new to this, so if this is extremely basic, I am sorry!

I am attempting to put a CSV file into a database. My issue is that it is not bringing in the time portion of the CSV correctly. Here is what I have written so far.

require 'csv'

desc "Import from CSV"
task :import => [:environment] do
    
    file = "lib/trans_items.csv"

    CSV.foreach(file, :headers => true) do |row|

        sale = Sale.find_or_initialize_by(
            location: row[0],
            trans_number: row[7]
        )
        sale.terminal = row[1],
        sale.customer = row[2],
        sale.license_plate = row[3],
        sale.controller_number = row[4],
        sale.complete_time = row[5],
        sale.status = row[6],
        sale.cashier = row[8],
        sale.greeter = row[9],
        sale.item_name = row[10],
        sale.item_department = row[11],
        sale.item_quantity = row[12],
        sale.item_amount = row[13],
        sale.discounts = row[14],
        sale.tax = row[15],
        sale.total = row[16]
        sale.save
    end
end

The date in the CSV is given like this: "01/29/2021 - 6:55 PM (CST)".

When I have tried using to_datetime and other date time methods, I get "Date::Error (invalid date)".

I am looking for a way to convert this string into the correct format before passing it into the database.

Thank you!

question from:https://stackoverflow.com/questions/66048797/how-would-you-convert-a-string-in-the-wrong-format-to-datetime

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I was able to get this problem figured out. Here is the code that I used. ''' sale.complete_time = DateTime.strptime(row[5], '%m/%d/%Y - %I:%M %p (%z)') '''


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...