Reputation: 59
Is there an easier way to insert a time stamp in a file name ?
def time_stamped_file(file)
file.gsub(/\./,"_" + Time.now.strftime("%m-%d_%H-%M-%S") + '.')
end
f = "test.txt"
puts time_stamped_file(f)
=> test_01-24_12-56-33.txt
Upvotes: 5
Views: 10930
Reputation: 41
What about this? It worked for me.
time = Time.now
puts time.strftime("%m-%d-%Y.%H.%M.%S")
Upvotes: 3
Reputation: 14268
If you're just trying to create a uniquely named file and it doesn't have to contain the original filename, you could use the built-in Tempfile class:
require 'tempfile'
file = Tempfile.new('test')
file.path
#=> "/var/folders/bz/j5rz8c2n379949sxn9gwn9gr0000gn/T/test20130124-72354-cwohwv"
Upvotes: 2
Reputation: 2411
If you want a shorter approach you (and dont care particularly about the accuracy of the the timestamp) you could adopt an approach similar to Paperclip as mention in the below SO post.
Paperclip - How do they create the timestamp appended to the file name?
Upvotes: 1
Reputation: 240044
Not necessarily "easier," but here's a slightly more canonical and robust way to do it:
def timestamp_filename(file)
dir = File.dirname(file)
base = File.basename(file, ".*")
time = Time.now.to_i # or format however you like
ext = File.extname(file)
File.join(dir, "#{base}_#{time}#{ext}")
end
timestamp_filename("test.txt") # => "./test_1359052544.txt"
timestamp_filename("test") # => "./test_1359052544"
timestamp_filename("dir/test.csv") # => "dir/test_1359052544.csv"
Upvotes: 10