Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a float of seconds since minimum in C#

Tags:

c#

datetime

I am porting a Python script to C#.

Currently I have encountered the code that uses

time.time()

As per Python documentation this function call returns a float of total count of seconds.

Return the time as a floating point number expressed in seconds since the epoch, in UTC. Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls.

How can I get the same from CLR?

like image 843
Maxim V. Pavlov Avatar asked Dec 30 '25 20:12

Maxim V. Pavlov


2 Answers

The start of "the Epoch" on Unix refers to January 1, 1970. That's a fairly arbitrary date, set to be "early enough" that anyone querying the time since that date would get a positive number of seconds.

 TimeSpan t = (DateTime.UtcNow - 
               new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc));
 float seconds  = (float) t.TotalSeconds;
 Console.WriteLine (seconds);

http://blogs.msdn.com/b/brada/archive/2004/03/20/93332.aspx

like image 182
Eric J. Avatar answered Jan 01 '26 10:01

Eric J.


Similar to the others, but I'd suggest making sure you use the Unix epoch in UTC, for sanity if nothing else:

private static readonly DateTime UnixEpoch =
    new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

...

TimeSpan timeSinceEpoch = DateTime.UtcNow - UnixEpoch;
double seconds = timeSinceEpoch.TotalSeconds;

(Note that I've kept the value as a double given that you apparently want it that way.)

Alternatively, using Noda Time:

// clock would normally be injected, or you could use SystemClock.Instance
Instant instant = clock.Now;
Duration duration = instant - Instant.UnixEpoch;

// Noda Time exposes TotalXyz as long, not double. Go from ticks here
double seconds = ((double) duration.TotalTicks) / NodaConstants.TicksPerSecond;
like image 31
Jon Skeet Avatar answered Jan 01 '26 10:01

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!