Petros Kyriakou Petros Kyriakou - 4 months ago 8
Ruby Question

How to convert date and time into datetime/timestamp

I need to import some CSV data and they have a date field and a time field of the format below

{"date"=>"23/04/16", "day"=>"SATURDAY", "time"=>"17:06"}


and i want to make that a timestamp and be the created_at field in the record.

What is the way to go about it?

Answer

You would use strptime on Time or DateTime

if you need timestamp:

require 'time'

csv_hash = {"date"=>"23/04/16", "day"=>"SATURDAY", "time"=>"17:06"}
time_from_csv = Time.strptime("#{csv_hash["date"]}:#{csv_hash["time"]}", '%d/%m/%y:%H:%M') # 2016-04-23 17:06:00 +0000
timestamp = time_from_csv.to_i # 1461423960

Take a read at the documentation for Time#strptime

If you want DateTime do DateTime.strptime(...)