Time Object convert to Time::Instant

Want to use Time::Instant which introduced in 1.19

But, my started_at come from file modified time

started_at = File.info(self.pid_file_path).modification_time # Time object

How to convert it into a Time::Instant object?

Then I can use like this: Time.instant.duration_since(started_at)

thanks


Perhaps duration_since should support Time as arg as well?

Comparing Time::Instant with a Time instance is impossible as they are based on entirely different timelines.
Time::Instant uses a clock that is specific to the current process. It’s not comparable to anything else but itself. See Time::Instant - Crystal 1.19.1

What you can do is relate readings from different clocks to each other.
If you take two readings Time.instant and Time.utc at the same time (or near same-time, such as directly after each other), you can establish a correlation between them.
Then you can calculate the difference between any Time instant and the Time.utc reading and add it to the Time.instant reading to get an approximate correspondence across timelines. But this of course only works as well as the Time.utc clock proceeds montonically in the respective time span.

corresponding_instant = Time.instant
corresponding_utc = Time.utc

started_at = File.info(path).modification_time
instant_started_at = corresponding_instant + (started_at - corresponding_utc)

honestly, if I were using it that way, I probably wouldn’t use time.instant since it’s a bit of a hassle. I often want to use it, what I want to do is accurately measure the time span, but keep running into conversion issues, unless it’s the simplest use case, such as:

time1 = Time.instant
# do somethings
time2 = Time.instant

Do we consider add a Time#to_instant like this:

class Time
  def to_instant
    Time.instant + (self - Time.utc)
  end
end

Then I can use like this:

Time.instant.duration_since(started_at.to_instant)

It simply doesn’t work that way.
I might not have been clear enough in the previous comment: Time and Time::Instant are conceptually completely different and behave very differently. They’re not comparable and any attempt to correlate them is extremely limited.
Time::Instant provides no benefit for your use case. It cannot provide better accuracy than Time when the source of measurement is a Time instance in the first place.