Datetime's Representation in Milliseconds

DateTime's representation in milliseconds?

You're probably trying to convert to a UNIX-like timestamp, which are in UTC:

yourDateTime.ToUniversalTime().Subtract(
new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
).TotalMilliseconds

This also avoids summertime issues, since UTC doesn't have those.

Format a datetime into a string with milliseconds

To get a date string with milliseconds, use [:-3] to trim the last three digits of %f (microseconds):

>>> from datetime import datetime
>>> datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
'2022-09-24 10:18:32.926'

Or slightly shorter:

>>> from datetime import datetime
>>> datetime.utcnow().strftime('%F %T.%f')[:-3]

How to store a Date time with milliseconds into a DateTime Object in C#?

I want to store the Data time in 01/01/2008 00:30:45.125 format as a key to in Dictionary.

DateTime objects do not have formats. They are binary data that represent a date and time. You can easily use a DateTime object with a value that represents the instant described by 01/01/2008 00:30:45.125 as a dictionary key, but that's not the same thing.

If you need a particular string format, use a string as the key type. But probably you're overthinking this, and you really don't want that particular string format in the Dictionary. After all, you can always take that DateTime object and format it for display later on, and that's really the better practice.

The remaining concern is DateTime has sub-millisecond precision, meaning you can have more than one DateTime value in a single millisecond. If it's possible for your environment to produce two data points within that same millisecond, and you want to make sure they end up in the same place in your dictionary, you'll need to truncate or round the DateTime value. I prefer to do this by constructing a new DateTime value using the properties from the old, though some calculation using Ticks is potentially faster:

public DateTime RoundToMillisecond(DateTime original)
{
return new DateTime(original.Year, original.Month, original.Day, original.Hour, original.Minute, original.Second, original.Millisecond);
}

Get time in milliseconds using C#

Use the Stopwatch class.

Provides a set of methods and
properties that you can use to
accurately measure elapsed time.

There is some good info on implementing it here:

Performance Tests: Precise Run Time Measurements with System.Diagnostics.Stopwatch



Related Topics



Leave a reply



Submit